55#define DEBUG_TYPE "loop-interchange"
57STATISTIC(LoopsInterchanged,
"Number of loops interchanged");
61 cl::desc(
"Interchange if you gain more than this number"));
65 cl::desc(
"Maximum number of load/store instructions squared in relation to "
66 "the total number of instructions. Higher value may lead to more "
67 "interchanges at the cost of compile-time"));
81using CharMatrix = std::vector<std::vector<char>>;
96 cl::desc(
"Minimum depth of loop nest considered for the transform"));
101 cl::desc(
"Maximum depth of loop nest considered for the transform"));
107 cl::desc(
"List of profitability heuristics to be used. They are applied in "
110 RuleTy::ForVectorization}),
112 "Prioritize loop cache cost"),
113 clEnumValN(RuleTy::PerInstrOrderCost,
"instorder",
114 "Prioritize the IVs order of each instruction"),
115 clEnumValN(RuleTy::ForVectorization,
"vectorize",
116 "Prioritize vectorization"),
118 "Ignore profitability, force interchange (does not "
119 "work with other options)")));
124 cl::desc(
"Support for the inner-loop reduction pattern."));
129 for (RuleTy Rule : Rules) {
130 if (!Set.insert(Rule).second)
132 if (Rule == RuleTy::Ignore)
139 for (
auto &Row : DepMatrix) {
152 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
153 "Expected Src and Dst to be different instructions in the same BB");
155 bool FoundSrc =
false;
176 unsigned NumInsts = 0;
204 unsigned NumMemInstr = MemInstr.
size();
206 <<
" Loads and Stores to analyze\n");
210 L->getStartLoc(), L->getHeader())
211 <<
"Number of loads/stores exceeded, the supported maximum can be "
212 "increased with option -loop-interchange-max-mem-instr-ratio.";
222 for (
I = MemInstr.
begin(), IE = MemInstr.
end();
I != IE; ++
I) {
223 for (J =
I, JE = MemInstr.
end(); J != JE; ++J) {
224 std::vector<char> Dep;
231 if (
auto D = DI->
depends(Src, Dst)) {
232 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
235 if (
D->normalize(SE))
238 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
239 dbgs() <<
"Found " << DepType
240 <<
" dependency between Src and Dst\n"
241 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
242 unsigned Levels =
D->getLevels();
244 for (
unsigned II = 1;
II <= Levels; ++
II) {
251 unsigned Dir =
D->getDirection(
II);
265 if (
D->isConfused()) {
266 assert(Dep.empty() &&
"Expected empty dependency vector");
267 Dep.assign(Level,
'*');
270 while (Dep.size() != Level) {
279 L->getStartLoc(), L->getHeader())
280 <<
"All loops have dependencies in all directions.";
286 bool IsKnownForward =
true;
287 if (Src->getParent() != Dst->getParent()) {
291 IsKnownForward =
false;
297 "Unexpected instructions");
302 bool IsReversed =
D->getSrc() != Src;
304 IsKnownForward =
false;
320 DepMatrix.push_back(Dep);
327 DepMatrix[Ite->second].back() =
'*';
339 for (
auto &Row : DepMatrix)
348static std::optional<bool>
361 unsigned InnerLoopId,
362 unsigned OuterLoopId) {
363 unsigned NumRows = DepMatrix.size();
364 std::vector<char> Cur;
366 for (
unsigned Row = 0; Row < NumRows; ++Row) {
369 Cur = DepMatrix[Row];
382 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
391 << L.getHeader()->getParent()->getName() <<
" Loop: %"
392 << L.getHeader()->getName() <<
'\n');
393 assert(LoopList.
empty() &&
"LoopList should initially be empty!");
394 Loop *CurrentLoop = &L;
395 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
396 while (!Vec->empty()) {
400 if (Vec->size() != 1) {
406 CurrentLoop = Vec->front();
414 unsigned LoopNestDepth = LoopList.
size();
416 LLVM_DEBUG(
dbgs() <<
"Unsupported depth of loop nest " << LoopNestDepth
424 <<
"Unsupported depth of loop nest, the supported range is ["
435 for (
Loop *L : LoopList) {
441 if (L->getNumBackEdges() != 1) {
445 if (!L->getExitingBlock()) {
456class LoopInterchangeLegality {
458 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
459 OptimizationRemarkEmitter *ORE, DominatorTree *DT)
460 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), DT(DT), ORE(ORE) {}
463 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
464 CharMatrix &DepMatrix);
468 bool findInductions(Loop *L, SmallVectorImpl<PHINode *> &Inductions);
472 bool isLoopStructureUnderstood();
474 bool currentLimitations();
476 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions()
const {
477 return OuterInnerReductions;
481 return InnerLoopInductions;
485 return HasNoWrapReductions;
494 struct InnerReduction {
502 StoreInst *LcssaStore;
509 return InnerReductions;
513 bool tightlyNested(Loop *Outer, Loop *Inner);
514 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
520 bool findInductionAndReductions(Loop *L,
534 bool isInnerReduction(Loop *L, PHINode *Phi,
535 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
544 OptimizationRemarkEmitter *ORE;
548 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
556 SmallVector<Instruction *, 4> HasNoWrapReductions;
560 SmallVector<Instruction *, 4> HasNoInfInsts;
569class CacheCostManager {
571 LoopStandardAnalysisResults *AR;
576 std::optional<std::unique_ptr<CacheCost>> CC;
580 DenseMap<const Loop *, unsigned> CostMap;
582 void computeIfUnitinialized();
585 CacheCostManager(Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
587 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
588 CacheCost *getCacheCost();
589 const DenseMap<const Loop *, unsigned> &getCostMap();
594class LoopInterchangeProfitability {
596 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
597 OptimizationRemarkEmitter *ORE)
598 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
601 bool isProfitable(
const Loop *InnerLoop,
const Loop *OuterLoop,
602 unsigned InnerLoopId,
unsigned OuterLoopId,
603 CharMatrix &DepMatrix, CacheCostManager &CCM);
606 int getInstrOrderCost();
607 std::optional<bool> isProfitablePerLoopCacheAnalysis(
608 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC);
609 std::optional<bool> isProfitablePerInstrOrderCost();
610 std::optional<bool> isProfitableForVectorization(
unsigned InnerLoopId,
611 unsigned OuterLoopId,
612 CharMatrix &DepMatrix);
620 OptimizationRemarkEmitter *ORE;
624class LoopInterchangeTransform {
626 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE,
627 LoopInfo *LI, DominatorTree *DT,
628 const LoopInterchangeLegality &LIL)
629 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
634 void reduction2Memory();
635 void restructureLoops(Loop *NewInner, Loop *NewOuter,
636 BasicBlock *OrigInnerPreHeader,
637 BasicBlock *OrigOuterPreHeader);
638 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop);
641 bool adjustLoopLinks();
642 bool adjustLoopBranches();
653 const LoopInterchangeLegality &LIL;
656struct LoopInterchange {
657 ScalarEvolution *SE =
nullptr;
658 LoopInfo *LI =
nullptr;
659 DependenceInfo *DI =
nullptr;
660 DominatorTree *DT =
nullptr;
661 LoopStandardAnalysisResults *AR =
nullptr;
664 OptimizationRemarkEmitter *ORE;
666 LoopInterchange(ScalarEvolution *SE, LoopInfo *LI, DependenceInfo *DI,
667 DominatorTree *DT, LoopStandardAnalysisResults *AR,
668 OptimizationRemarkEmitter *ORE)
669 : SE(SE), LI(LI), DI(DI), DT(DT), AR(AR), ORE(ORE) {}
672 if (
L->getParentLoop())
674 SmallVector<Loop *, 8> LoopList;
676 return processLoopList(LoopList);
679 bool run(LoopNest &LN) {
680 SmallVector<Loop *, 8> LoopList(LN.
getLoops());
681 for (
unsigned I = 1;
I < LoopList.size(); ++
I)
682 if (LoopList[
I]->getParentLoop() != LoopList[
I - 1])
684 return processLoopList(LoopList);
690 return LoopList.
size() - 1;
693 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
698 "Unsupported depth of loop nest.");
700 unsigned LoopNestDepth = LoopList.
size();
703 dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
704 <<
" containing the following loops:\n";
705 for (
auto *L : LoopList) {
711 CharMatrix DependencyMatrix;
712 Loop *OuterMostLoop = *(LoopList.begin());
714 OuterMostLoop, DI, SE, ORE)) {
726 <<
"' needs an unique exit block");
730 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
731 CacheCostManager CCM(LoopList[0], AR, DI);
736 for (
unsigned j = SelecLoopId;
j > 0;
j--) {
737 bool ChangedPerIter =
false;
738 for (
unsigned i = SelecLoopId; i > SelecLoopId -
j; i--) {
740 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
741 ChangedPerIter |= Interchanged;
752 bool processLoop(SmallVectorImpl<Loop *> &LoopList,
unsigned InnerLoopId,
753 unsigned OuterLoopId,
754 std::vector<std::vector<char>> &DependencyMatrix,
755 CacheCostManager &CCM) {
756 Loop *OuterLoop = LoopList[OuterLoopId];
757 Loop *InnerLoop = LoopList[InnerLoopId];
759 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
760 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE, DT);
761 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
762 LLVM_DEBUG(
dbgs() <<
"Cannot prove legality, not interchanging loops '"
763 << OuterLoop->
getName() <<
"' and '"
764 << InnerLoop->
getName() <<
"'\n");
769 <<
"' are legal to interchange\n");
770 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE);
771 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
772 DependencyMatrix, CCM)) {
774 <<
"' and '" << InnerLoop->
getName()
775 <<
"' not profitable.\n");
780 return OptimizationRemark(
DEBUG_TYPE,
"Interchanged",
783 <<
"Loop interchanged with enclosing loop.";
786 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
787 LIT.transform(LIL.getHasNoWrapReductions(), LIL.getHasNoInfInsts());
789 << OuterLoop->
getName() <<
"' and inner loop '"
790 << InnerLoop->
getName() <<
"'\n");
796 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
809bool LoopInterchangeLegality::containsUnsafeInstructions(
BasicBlock *BB,
811 return any_of(*BB, [Skip](
const Instruction &
I) {
814 return I.mayHaveSideEffects() ||
I.mayReadFromMemory();
818bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) {
824 <<
"' and '" << InnerLoop->
getName()
825 <<
"' are tightly nested\n");
830 for (BasicBlock *Succ :
successors(OuterLoopHeader))
831 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->
getHeader() &&
832 Succ != OuterLoopLatch)
835 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
841 assert(InnerReductions.size() <= 1 &&
842 "So far we only support at most one reduction.");
843 if (InnerReductions.size() == 1)
844 Skip = InnerReductions[0].LcssaStore;
848 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
849 containsUnsafeInstructions(OuterLoopLatch, Skip))
855 if (InnerLoopPreHeader != OuterLoopHeader &&
856 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
864 if (&SuccInner != OuterLoopLatch) {
866 <<
" does not lead to the outer loop latch.\n";);
872 if (containsUnsafeInstructions(InnerLoopExit, Skip))
880bool LoopInterchangeLegality::isLoopStructureUnderstood() {
882 for (PHINode *InnerInduction : InnerLoopInductions) {
883 unsigned Num = InnerInduction->getNumOperands();
884 for (
unsigned i = 0; i < Num; ++i) {
885 Value *Val = InnerInduction->getOperand(i);
895 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
896 InnerLoopPreheader &&
910 CondBrInst *InnerLoopLatchBI =
912 if (!InnerLoopLatchBI)
914 if (CmpInst *InnerLoopCmp =
916 Value *Op0 = InnerLoopCmp->getOperand(0);
917 Value *Op1 = InnerLoopCmp->getOperand(1);
928 std::function<bool(
Value *)> IsPathToInnerIndVar;
929 IsPathToInnerIndVar = [
this, &IsPathToInnerIndVar](
const Value *
V) ->
bool {
938 return IsPathToInnerIndVar(
I->getOperand(0));
940 return IsPathToInnerIndVar(
I->getOperand(0)) &&
941 IsPathToInnerIndVar(
I->getOperand(1));
947 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
955 }
else if (IsPathToInnerIndVar(Op1) && !
isa<Constant>(Op1)) {
978 if (
PHI->getNumIncomingValues() != 1)
1046 assert(
I->getOpcode() == OpCode &&
1047 "Expected the instruction to be the reduction operation");
1052 if (
I->hasNoSignedWrap() ||
I->hasNoUnsignedWrap())
1076 if (
PHI->getNumIncomingValues() == 1)
1089bool LoopInterchangeLegality::isInnerReduction(
1090 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1094 if (!
L->isInnermost()) {
1095 LLVM_DEBUG(
dbgs() <<
"Only supported when the loop is the innermost.\n");
1097 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1098 L->getStartLoc(),
L->getHeader())
1099 <<
"Only supported when the loop is the innermost.";
1104 if (
Phi->getNumIncomingValues() != 2)
1107 Value *Init =
Phi->getIncomingValueForBlock(
L->getLoopPreheader());
1108 Value *
Next =
Phi->getIncomingValueForBlock(
L->getLoopLatch());
1114 <<
"Only supported for the reduction with a constant initial value.\n");
1116 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1117 L->getStartLoc(),
L->getHeader())
1118 <<
"Only supported for the reduction with a constant initial "
1127 if (!
L->contains(BB))
1132 if (!
Phi->hasOneUser())
1144 PHINode *Lcssa = NULL;
1145 for (
auto *U :
Next->users()) {
1150 if (Lcssa == NULL &&
P->getParent() == ExitBlock &&
1151 P->getIncomingValueForBlock(
L->getLoopLatch()) ==
Next)
1162 LLVM_DEBUG(
dbgs() <<
"Only supported when the reduction is used once in "
1163 "the outer loop.\n");
1165 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1166 L->getStartLoc(),
L->getHeader())
1167 <<
"Only supported when the reduction is used once in the outer "
1173 StoreInst *LcssaStore =
1175 if (!LcssaStore || LcssaStore->
getParent() != ExitBlock)
1188 LLVM_DEBUG(
dbgs() <<
"Only supported when memory reference dominate "
1189 "the inner loop.\n");
1191 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1192 L->getStartLoc(),
L->getHeader())
1193 <<
"Only supported when memory reference dominate the inner "
1204 SR.LcssaPhi = Lcssa;
1205 SR.LcssaStore = LcssaStore;
1209 InnerReductions.push_back(SR);
1213bool LoopInterchangeLegality::findInductionAndReductions(
1215 if (!
L->getLoopLatch() || !
L->getLoopPredecessor())
1217 for (PHINode &
PHI :
L->getHeader()->phis()) {
1218 InductionDescriptor
ID;
1225 if (OuterInnerReductions.count(&
PHI)) {
1226 LLVM_DEBUG(
dbgs() <<
"Found a reduction across the outer loop.\n");
1228 isInnerReduction(L, &
PHI, HasNoWrapReductions)) {
1234 assert(
PHI.getNumIncomingValues() == 2 &&
1235 "Phis in loop header should have exactly 2 incoming values");
1240 InnerLoop, V, HasNoWrapReductions, HasNoInfInsts);
1245 <<
"Failed to recognize PHI as an induction or reduction.\n");
1248 OuterInnerReductions.insert(&
PHI);
1249 OuterInnerReductions.insert(InnerRedPhi);
1255 if (InnerReductions.size() > 1) {
1258 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1259 L->getStartLoc(),
L->getHeader())
1260 <<
"Only supports at most one reduction.";
1270bool LoopInterchangeLegality::currentLimitations() {
1280 dbgs() <<
"Loops where the latch is not the exiting block are not"
1281 <<
" supported currently.\n");
1283 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ExitingNotLatch",
1286 <<
"Loops where the latch is not the exiting block cannot be"
1287 " interchange currently.";
1293 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) {
1295 dbgs() <<
"Only outer loops with induction or reduction PHI nodes "
1296 <<
"are supported currently.\n");
1298 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIOuter",
1301 <<
"Only outer loops with induction or reduction PHI nodes can be"
1302 " interchanged currently.";
1311 Loop *CurLevelLoop = OuterLoop;
1314 CurLevelLoop = CurLevelLoop->
getSubLoops().front();
1315 if (!findInductionAndReductions(CurLevelLoop, Inductions,
nullptr)) {
1317 dbgs() <<
"Only inner loops with induction or reduction PHI nodes "
1318 <<
"are supported currently.\n");
1320 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIInner",
1323 <<
"Only inner loops with induction or reduction PHI nodes can be"
1324 " interchange currently.";
1331 if (!isLoopStructureUnderstood()) {
1334 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedStructureInner",
1337 <<
"Inner loop structure not understood currently.";
1345bool LoopInterchangeLegality::findInductions(
1346 Loop *L, SmallVectorImpl<PHINode *> &Inductions) {
1347 for (PHINode &
PHI :
L->getHeader()->phis()) {
1348 InductionDescriptor
ID;
1352 return !Inductions.
empty();
1372 if (
PHI.getNumIncomingValues() > 1)
1374 if (&
PHI == LcssaReduction)
1377 PHINode *PN = dyn_cast<PHINode>(U);
1380 if (Reductions.count(PN))
1382 BasicBlock *PB = PN->getParent();
1383 if (!OuterL->contains(PB))
1385 return PB != OuterL->getLoopLatch();
1402 for (
Value *Incoming :
PHI.incoming_values()) {
1449 for (
auto *U :
PHI.users()) {
1458bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
1459 unsigned OuterLoopId,
1460 CharMatrix &DepMatrix) {
1462 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
1463 <<
" and OuterLoopId = " << OuterLoopId
1464 <<
" due to dependence\n");
1466 return OptimizationRemarkMissed(
DEBUG_TYPE,
"Dependence",
1469 <<
"Cannot interchange loops due to dependences.";
1474 for (
auto *BB : OuterLoop->
blocks())
1475 for (Instruction &
I : *BB)
1481 dbgs() <<
"Loops with call instructions cannot be interchanged "
1484 return OptimizationRemarkMissed(
DEBUG_TYPE,
"CallInst",
1487 <<
"Cannot interchange loops due to call instruction.";
1493 if (!findInductions(InnerLoop, InnerLoopInductions)) {
1494 LLVM_DEBUG(
dbgs() <<
"Could not find inner loop induction variables.\n");
1499 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop latch.\n");
1501 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerLatchPHI",
1504 <<
"Cannot interchange loops because unsupported PHI nodes found "
1505 "in inner loop latch.";
1512 if (currentLimitations()) {
1513 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
1518 if (!tightlyNested(OuterLoop, InnerLoop)) {
1521 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotTightlyNested",
1524 <<
"Cannot interchange loops because they are not tightly "
1532 PHINode *LcssaReduction =
nullptr;
1533 assert(InnerReductions.size() <= 1 &&
1534 "So far we only support at most one reduction.");
1535 if (InnerReductions.size() == 1)
1536 LcssaReduction = InnerReductions[0].LcssaPhi;
1540 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop exit.\n");
1542 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1545 <<
"Found unsupported PHI node in loop exit.";
1551 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1553 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1556 <<
"Found unsupported PHI node in loop exit.";
1562 [](PHINode &
PHI) { return PHI.getNumIncomingValues() != 1; })) {
1563 LLVM_DEBUG(
dbgs() <<
"Only outer loop latch PHI nodes with one incoming "
1564 "value are supported.\n");
1566 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedLatchPHI",
1569 <<
"Only outer loop latch PHI nodes with one incoming value are "
1578void CacheCostManager::computeIfUnitinialized() {
1593 for (
const auto &[Idx,
Cost] :
enumerate((*CC)->getLoopCosts()))
1594 CostMap[
Cost.first] = Idx;
1597CacheCost *CacheCostManager::getCacheCost() {
1598 computeIfUnitinialized();
1602const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1603 computeIfUnitinialized();
1619 return std::nullopt;
1624 return std::nullopt;
1627 std::optional<const SCEV *> Coeff =
1629 if (!Coeff.has_value())
1630 return std::nullopt;
1633 assert(!*Coeff &&
"Found more than one addrec for the same loop");
1639int LoopInterchangeProfitability::getInstrOrderCost() {
1640 SmallPtrSet<const SCEV *, 4> GoodBasePtrs, BadBasePtrs;
1641 for (BasicBlock *BB : InnerLoop->
blocks()) {
1642 for (Instruction &Ins : *BB) {
1647 std::optional<const SCEV *> OuterCoeff =
1649 std::optional<const SCEV *> InnerCoeff =
1652 if (!OuterCoeff.has_value() || !*OuterCoeff || !InnerCoeff.has_value() ||
1662 const SCEV *OuterStep = SE->
getAbsExpr(*OuterCoeff,
false);
1663 const SCEV *InnerStep = SE->
getAbsExpr(*InnerCoeff,
false);
1683 GoodBasePtrs.
insert(BasePtr);
1685 BadBasePtrs.
insert(BasePtr);
1689 int GoodOrder = GoodBasePtrs.
size();
1690 int BadOrder = BadBasePtrs.
size();
1691 return GoodOrder - BadOrder;
1695LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1696 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *CC) {
1700 auto InnerLoopIt = CostMap.
find(InnerLoop);
1701 if (InnerLoopIt == CostMap.
end())
1702 return std::nullopt;
1703 auto OuterLoopIt = CostMap.
find(OuterLoop);
1704 if (OuterLoopIt == CostMap.
end())
1705 return std::nullopt;
1708 return std::nullopt;
1709 unsigned InnerIndex = InnerLoopIt->second;
1710 unsigned OuterIndex = OuterLoopIt->second;
1712 <<
", OuterIndex = " << OuterIndex <<
"\n");
1713 assert(InnerIndex != OuterIndex &&
"CostMap should assign unique "
1714 "numbers to each loop");
1715 return std::optional<bool>(InnerIndex < OuterIndex);
1719LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1723 int Cost = getInstrOrderCost();
1726 return std::optional<bool>(
true);
1728 return std::nullopt;
1733 for (
const auto &Dep : DepMatrix) {
1734 char Dir = Dep[LoopId];
1735 char DepType = Dep.back();
1736 assert((DepType ==
'<' || DepType ==
'*') &&
1737 "Unexpected element in dependency vector");
1740 if (Dir ==
'=' || Dir ==
'I')
1746 if (Dir ==
'<' && DepType ==
'<')
1755std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1756 unsigned InnerLoopId,
unsigned OuterLoopId, CharMatrix &DepMatrix) {
1772 return std::nullopt;
1775bool LoopInterchangeProfitability::isProfitable(
1776 const Loop *InnerLoop,
const Loop *OuterLoop,
unsigned InnerLoopId,
1777 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
1786 if (InnerBTC && InnerBTC->
isZero()) {
1787 LLVM_DEBUG(
dbgs() <<
"Inner loop back-edge isn't taken, rejecting "
1788 "single iteration loop\n");
1791 if (OuterBTC && OuterBTC->
isZero()) {
1792 LLVM_DEBUG(
dbgs() <<
"Outer loop back-edge isn't taken, rejecting "
1793 "single iteration loop\n");
1801 "Duplicate rules and option 'ignore' are not allowed");
1811 std::optional<bool> shouldInterchange;
1814 case RuleTy::PerLoopCacheAnalysis: {
1815 CacheCost *CC = CCM.getCacheCost();
1816 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
1817 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap, CC);
1820 case RuleTy::PerInstrOrderCost:
1821 shouldInterchange = isProfitablePerInstrOrderCost();
1823 case RuleTy::ForVectorization:
1825 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
1827 case RuleTy::Ignore:
1834 if (shouldInterchange.has_value())
1838 if (!shouldInterchange.has_value()) {
1840 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
1843 <<
"Insufficient information to calculate the cost of loop for "
1847 }
else if (!shouldInterchange.value()) {
1849 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
1852 <<
"Interchanging loops is not considered to improve cache "
1853 "locality nor vectorization.";
1860void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop,
1862 for (Loop *L : *OuterLoop)
1863 if (L == InnerLoop) {
1864 OuterLoop->removeChildLoop(L);
1893void LoopInterchangeTransform::restructureLoops(
1894 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
1895 BasicBlock *OrigOuterPreHeader) {
1896 Loop *OuterLoopParent = OuterLoop->getParentLoop();
1903 if (OuterLoopParent) {
1905 removeChildLoop(OuterLoopParent, NewInner);
1906 removeChildLoop(NewInner, NewOuter);
1909 removeChildLoop(NewInner, NewOuter);
1917 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->
blocks());
1921 for (BasicBlock *BB : NewInner->
blocks())
1929 for (BasicBlock *BB : OrigInnerBBs) {
1934 if (BB == OuterHeader || BB == OuterLatch)
1972void LoopInterchangeTransform::reduction2Memory() {
1974 LIL.getInnerReductions();
1977 "So far we only support at most one reduction.");
1979 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
1985 PHINode *FirstIter =
1986 Builder.CreatePHI(Type::getInt1Ty(
Context), 2,
"first.iter");
1991 assert(FirstIter->
isComplete() &&
"The FirstIter PHI node is not complete.");
1996 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
1999 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem,
"new.var");
2010bool LoopInterchangeTransform::transform(
2013 bool Transformed =
false;
2016 LIL.getInnerReductions();
2017 if (InnerReductions.
size() == 1)
2021 auto &InductionPHIs = LIL.getInnerLoopInductions();
2022 if (InductionPHIs.empty()) {
2023 LLVM_DEBUG(
dbgs() <<
"Failed to find the point to split loop latch \n");
2027 SmallVector<Instruction *, 8> InnerIndexVarList;
2028 for (PHINode *CurInductionPHI : InductionPHIs) {
2030 CurInductionPHI->getIncomingValueForBlock(InnerLoop->
getLoopLatch()));
2032 "Incoming value from loop latch isn't an instruction");
2035 InnerIndexVarList.
push_back(IncomingValue);
2046 SmallSetVector<Instruction *, 4> WorkList;
2048 auto MoveInstructions = [&i, &WorkList,
this, &InductionPHIs, NewLatch]() {
2049 for (; i < WorkList.
size(); i++) {
2055 "Moving instructions with side-effects may change behavior of "
2066 for (
Value *
Op : WorkList[i]->operands()) {
2083 for (Instruction *InnerIndexVar : InnerIndexVarList)
2101 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2103 if (InnerLoopPreHeader != OuterLoopHeader) {
2106 assert(
P.getNumIncomingValues() == 1 &&
2107 "Expected single-incoming PHIs in inner loop preheader");
2108 P.replaceAllUsesWith(
P.getIncomingValue(0));
2109 P.eraseFromParent();
2111 for (Instruction &
I :
2113 std::prev(InnerLoopPreHeader->
end()))))
2117 Transformed |= adjustLoopLinks();
2125 for (Instruction *
Reduction : DropNoWrapInsts) {
2129 for (Instruction *
I : DropNoInfInsts)
2130 I->setHasNoInfs(
false);
2151 I->removeFromParent();
2166 std::vector<DominatorTree::UpdateType> &DTUpdates,
2167 bool MustUpdateOnce =
true) {
2169 "BI must jump to OldBB exactly once.");
2171 for (
Use &
Op : Term->operands())
2178 DTUpdates.push_back(
2179 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2180 DTUpdates.push_back(
2181 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2200 assert(
P.getNumIncomingValues() == 1 &&
2201 "Only loops with a single exit are supported!");
2210 if (IncIInnerMost->getParent() != InnerLatch &&
2211 IncIInnerMost->
getParent() != InnerHeader)
2215 [OuterHeader, OuterExit, IncI, InnerHeader](
User *U) {
2216 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2217 IncI->getParent() == InnerHeader) ||
2218 cast<PHINode>(U)->getParent() == OuterExit;
2220 "Can only replace phis iff the uses are in the loop nest exit or "
2221 "the incoming value is defined in the inner header (it will "
2222 "dominate all loop blocks after interchanging)");
2223 P.replaceAllUsesWith(IncI);
2224 P.eraseFromParent();
2252 if (
P.getNumIncomingValues() != 1)
2266 if (Pred == OuterLatch)
2271 P.setIncomingValue(0, NewPhi);
2311 if (OuterLoopLatch == InnerLoopExit)
2318 assert(Phi->getNumIncomingValues() == 1 &&
"Single input phi expected");
2319 LLVM_DEBUG(
dbgs() <<
"Removing 1-input phi in non-exit block: " << *Phi
2321 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2322 Phi->eraseFromParent();
2326bool LoopInterchangeTransform::adjustLoopBranches() {
2328 std::vector<DominatorTree::UpdateType> DTUpdates;
2330 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2333 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2334 InnerLoopPreHeader != InnerLoop->
getHeader() && OuterLoopPreHeader &&
2335 InnerLoopPreHeader &&
"Guaranteed by loop-simplify form");
2345 OuterLoopPreHeader =
2347 if (InnerLoopPreHeader == OuterLoop->getHeader())
2348 InnerLoopPreHeader =
2353 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2355 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2362 CondBrInst *OuterLoopLatchBI =
2364 CondBrInst *InnerLoopLatchBI =
2369 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
2370 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
2378 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
2381 if (!InnerLoopHeaderSuccessor)
2389 InnerLoopPreHeader, DTUpdates,
false);
2399 InnerLoopHeaderSuccessor, DTUpdates,
2407 OuterLoopPreHeader, DTUpdates);
2410 if (InnerLoopLatchBI->
getSuccessor(0) == InnerLoopHeader)
2411 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(1);
2413 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(0);
2416 InnerLoopLatchSuccessor, DTUpdates);
2418 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
2419 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
2421 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
2424 OuterLoopLatchSuccessor, DTUpdates);
2425 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2429 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2430 OuterLoopPreHeader);
2432 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2433 OuterLoopHeader, OuterLoopLatch, InnerLoop->
getExitBlock(),
2439 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2442 for (PHINode &
PHI : InnerLoopHeader->
phis())
2443 if (OuterInnerReductions.contains(&
PHI))
2446 for (PHINode &
PHI : OuterLoopHeader->
phis())
2447 if (OuterInnerReductions.contains(&
PHI))
2453 for (PHINode *
PHI : OuterLoopPHIs) {
2456 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2458 for (PHINode *
PHI : InnerLoopPHIs) {
2461 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2474 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2475 for (Instruction &
I :
2483bool LoopInterchangeTransform::adjustLoopLinks() {
2485 bool Changed = adjustLoopBranches();
2490 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2511 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
2519 <<
"Computed dependence info, invoking the transform.";
2523 if (!LoopInterchange(&AR.
SE, &AR.
LI, &DI, &AR.
DT, &AR, &ORE).run(LN))
2525 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::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::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 cl::opt< int > LoopInterchangeCostThreshold("loop-interchange-threshold", cl::init(0), cl::Hidden, cl::desc("Interchange if you gain more than this number"))
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)
std::optional< const SCEV * > getAddRecCoefficient(ScalarEvolution &SE, const SCEV *S, const Loop *L)
If \S contains an affine addrec for L, return the step recurrence of it.
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 cl::opt< unsigned int > MaxMemInstrRatio("loop-interchange-max-mem-instr-ratio", cl::init(4), cl::Hidden, cl::desc("Maximum number of load/store instructions squared in relation to " "the total number of instructions. Higher value may lead to more " "interchanges at the cost of compile-time"))
static void swapBBContents(BasicBlock *BB1, BasicBlock *BB2)
Swap instructions between BB1 and BB2 but keep terminators intact.
static PHINode * findInnerReductionPhi(Loop *L, Value *V, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
static bool areInnerLoopExitPHIsSupported(Loop *OuterL, Loop *InnerL, SmallPtrSetImpl< PHINode * > &Reductions, PHINode *LcssaReduction)
We currently only support LCSSA PHI nodes in the inner loop exit if their users are either of the fol...
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 populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static std::optional< bool > isLexicographicallyPositive(ArrayRef< char > DV, unsigned Begin, unsigned End)
static bool checkReductionKind(Loop *L, PHINode *PHI, SmallVectorImpl< Instruction * > &HasNoWrapInsts, SmallVectorImpl< Instruction * > &HasNoInfInsts)
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)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
size_t size() const
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 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; assumes that the block is well-formed.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
static LLVM_ABI 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, ArrayRef< const SCEVPredicate * > NoWrapPreds={}, 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.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
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
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
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 * getAbsExpr(const SCEV *Op, bool IsNSW)
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 const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
Represent a constant reference to a string, i.e.
constexpr size_t size() const
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)
DXILDebugInfoMap run(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)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
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.
LLVM_ABI 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...