58#define DEBUG_TYPE "loop-interchange"
60STATISTIC(LoopsInterchanged,
"Number of loops interchanged");
74using CharMatrix = std::vector<std::vector<char>>;
86 if (!Set.insert(Rule).second)
95 for (
auto &Row : DepMatrix) {
108 assert(Src->getParent() == Dst->getParent() && Src != Dst &&
109 "Expected Src and Dst to be different instructions in the same BB");
111 bool FoundSrc =
false;
126 CharMatrix &DepMatrix,
unsigned Level,
133 unsigned NumInsts = 0;
159 unsigned NumMemInstr = MemInstr.
size();
161 <<
" Loads and Stores to analyze\n");
162 if (
static_cast<uint64_t>(Opts.loop_interchange_max_mem_instr_ratio) *
164 static_cast<uint64_t>(NumMemInstr) * NumMemInstr) {
167 L->getStartLoc(), L->getHeader())
168 <<
"Number of loads/stores exceeded, the supported maximum can be "
169 "increased with option -loop-interchange-max-mem-instr-ratio.";
179 for (
I = MemInstr.
begin(), IE = MemInstr.
end();
I != IE; ++
I) {
180 for (J =
I, JE = MemInstr.
end(); J != JE; ++J) {
181 std::vector<char> Dep;
188 if (
auto D = DI->
depends(Src, Dst)) {
189 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
192 if (
D->normalize(SE))
195 D->isFlow() ?
"flow" :
D->isAnti() ?
"anti" :
"output";
196 dbgs() <<
"Found " << DepType
197 <<
" dependency between Src and Dst\n"
198 <<
" Src:" << *Src <<
"\n Dst:" << *Dst <<
'\n');
199 unsigned Levels =
D->getLevels();
201 for (
unsigned II = 1;
II <= Levels; ++
II) {
208 unsigned Dir =
D->getDirection(
II);
222 if (
D->isConfused()) {
223 assert(Dep.empty() &&
"Expected empty dependency vector");
224 Dep.assign(L->getLoopDepth() + Level - 1,
'*');
227 while (Dep.size() < L->getLoopDepth() + Level - 1) {
234 if (Dep.size() > Level)
235 Dep.erase(Dep.begin(), Dep.end() - Level);
242 L->getStartLoc(), L->getHeader())
243 <<
"All loops have dependencies in all directions.";
249 bool IsKnownForward =
true;
250 if (Src->getParent() != Dst->getParent()) {
254 IsKnownForward =
false;
260 "Unexpected instructions");
265 bool IsReversed =
D->getSrc() != Src;
267 IsKnownForward =
false;
283 DepMatrix.push_back(Dep);
290 DepMatrix[Ite->second].back() =
'*';
302 for (
auto &Row : DepMatrix)
311static std::optional<bool>
324 unsigned InnerLoopId,
325 unsigned OuterLoopId) {
326 unsigned NumRows = DepMatrix.size();
327 std::vector<char> Cur;
329 for (
unsigned Row = 0; Row < NumRows; ++Row) {
332 Cur = DepMatrix[Row];
345 std::swap(Cur[InnerLoopId], Cur[OuterLoopId]);
354 << L.getHeader()->getParent()->getName() <<
" Loop: %"
355 << L.getHeader()->getName() <<
'\n');
356 assert(LoopList.
empty() &&
"LoopList should initially be empty!");
357 Loop *CurrentLoop = &L;
358 const std::vector<Loop *> *Vec = &CurrentLoop->
getSubLoops();
359 while (!Vec->empty()) {
363 if (Vec->size() != 1) {
369 CurrentLoop = Vec->front();
378 unsigned LoopNestDepth = LoopList.
size();
379 if (LoopNestDepth < Opts.loop_interchange_min_loop_nest_depth ||
380 LoopNestDepth > Opts.loop_interchange_max_loop_nest_depth) {
381 LLVM_DEBUG(
dbgs() <<
"Unsupported depth of loop nest " << LoopNestDepth
382 <<
", the supported range is ["
383 << Opts.loop_interchange_min_loop_nest_depth <<
", "
384 << Opts.loop_interchange_max_loop_nest_depth <<
"].\n");
390 <<
"Unsupported depth of loop nest, the supported range is ["
391 << std::to_string(Opts.loop_interchange_min_loop_nest_depth)
393 << std::to_string(Opts.loop_interchange_max_loop_nest_depth)
403 for (
Loop *L : LoopList) {
409 if (L->getNumBackEdges() != 1) {
413 if (!L->getExitingBlock()) {
424class LoopInterchangeLegality {
426 LoopInterchangeLegality(
const ScalarOptions &Opts,
Loop *Outer,
Loop *Inner,
427 ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,
429 : Opts(Opts), OuterLoop(
Outer), InnerLoop(Inner), SE(SE), DT(DT),
433 bool canInterchangeLoops(
unsigned InnerLoopId,
unsigned OuterLoopId,
434 CharMatrix &DepMatrix);
438 bool isLoopStructureUnderstood();
440 bool currentLimitations();
442 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions()
const {
443 return OuterInnerReductions;
447 return InnerLoopInductions;
450 ArrayRef<Instruction *> getHasNoWrapReductions()
const {
451 return HasNoWrapReductions;
454 ArrayRef<Instruction *> getHasNoInfInsts()
const {
return HasNoInfInsts; }
460 struct InnerReduction {
468 StoreInst *LcssaStore;
476 SmallVector<Instruction *, 4> AddressInstsToHoist;
480 return InnerReductions;
484 bool tightlyNested(
Loop *Outer,
Loop *Inner);
485 bool containsUnsafeInstructions(BasicBlock *BB, Instruction *Skip);
490 bool collectAddressInstsToHoist(
Value *
V,
Loop *InnerL,
491 SmallVectorImpl<Instruction *> &AddressInsts,
492 SmallPtrSetImpl<Instruction *> &Visited);
504 bool checkInductionsAndReductions(
Loop *OuterLoop);
516 bool isInnerReduction(
Loop *L, PHINode *Phi,
517 SmallVectorImpl<Instruction *> &HasNoWrapInsts);
519 const ScalarOptions &Opts;
527 OptimizationRemarkEmitter *ORE;
531 SmallPtrSet<PHINode *, 4> OuterInnerReductions;
539 SmallVector<Instruction *, 4> HasNoWrapReductions;
543 SmallVector<Instruction *, 4> HasNoInfInsts;
552class CacheCostManager {
554 LoopStandardAnalysisResults *AR;
559 std::optional<std::unique_ptr<CacheCost>> CC;
563 DenseMap<const Loop *, unsigned> CostMap;
565 void computeIfUnitinialized();
568 CacheCostManager(
Loop *OutermostLoop, LoopStandardAnalysisResults *AR,
570 : OutermostLoop(OutermostLoop), AR(AR), DI(DI) {}
571 CacheCost *getCacheCost();
572 const DenseMap<const Loop *, unsigned> &getCostMap();
577class LoopInterchangeProfitability {
579 LoopInterchangeProfitability(
const ScalarOptions &Opts,
Loop *Outer,
580 Loop *Inner, ScalarEvolution *SE,
581 OptimizationRemarkEmitter *ORE)
582 : Opts(Opts), OuterLoop(
Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {}
586 unsigned InnerLoopId,
unsigned OuterLoopId,
587 CharMatrix &DepMatrix, CacheCostManager &CCM);
590 int getInstrOrderCost();
591 std::optional<bool> isProfitablePerLoopCacheAnalysis(
592 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *
CC);
593 std::optional<bool> isProfitablePerInstrOrderCost();
594 std::optional<bool> isProfitableForVectorization(
unsigned InnerLoopId,
595 unsigned OuterLoopId,
596 CharMatrix &DepMatrix);
597 const ScalarOptions &Opts;
605 OptimizationRemarkEmitter *ORE;
609class LoopInterchangeTransform {
611 LoopInterchangeTransform(
Loop *Outer,
Loop *Inner, ScalarEvolution *SE,
612 LoopInfo *LI, DominatorTree *DT,
613 const LoopInterchangeLegality &LIL)
614 : OuterLoop(
Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), LIL(LIL) {}
617 void transform(ArrayRef<Instruction *> DropNoWrapInsts,
618 ArrayRef<Instruction *> DropNoInfInsts);
619 void reduction2Memory();
620 void restructureLoops(
Loop *NewInner,
Loop *NewOuter,
621 BasicBlock *OrigInnerPreHeader,
622 BasicBlock *OrigOuterPreHeader);
623 void removeChildLoop(
Loop *OuterLoop,
Loop *InnerLoop);
626 void adjustLoopBranches();
637 const LoopInterchangeLegality &LIL;
640struct LoopInterchange {
641 const ScalarOptions &Opts;
642 ScalarEvolution *SE =
nullptr;
643 LoopInfo *LI =
nullptr;
644 DependenceInfo *DI =
nullptr;
645 DominatorTree *DT =
nullptr;
646 LoopStandardAnalysisResults *AR =
nullptr;
649 OptimizationRemarkEmitter *ORE;
651 LoopInterchange(
const ScalarOptions &Opts, ScalarEvolution *SE, LoopInfo *LI,
652 DependenceInfo *DI, DominatorTree *DT,
653 LoopStandardAnalysisResults *AR,
654 OptimizationRemarkEmitter *ORE)
655 : Opts(Opts), SE(SE), LI(LI), DI(DI), DT(DT), AR(AR), ORE(ORE) {}
658 if (
L->getParentLoop())
660 SmallVector<Loop *, 8> LoopList;
662 return processLoopList(LoopList);
682 collectPerfectNests(LoopNest &LN) {
685 if (!
L->isInnermost())
688 SmallVector<Loop *, 8> LoopList;
697 std::reverse(LoopList.
begin(), LoopList.
end());
698 if (LoopList.
size() >= 2)
699 LoopLists.
push_back(std::move(LoopList));
704 bool run(LoopNest &LN) {
706 if (LoopLists.
empty()) {
707 LLVM_DEBUG(
dbgs() <<
"No Valid candidates for loop interchange.\n");
711 for (SmallVector<Loop *, 8> &LoopList : LoopLists) {
717 LLVM_DEBUG(
dbgs() <<
"Not valid loop candidate for interchange\n");
720 Changed |= processLoopList(LoopList);
728 return LoopList.
size() - 1;
731 bool processLoopList(SmallVectorImpl<Loop *> &LoopList) {
736 "Unsupported depth of loop nest.");
738 unsigned LoopNestDepth = LoopList.
size();
741 dbgs() <<
"Processing LoopList of size = " << LoopNestDepth
742 <<
" containing the following loops:\n";
743 for (
auto *L : LoopList) {
749 CharMatrix DependencyMatrix;
750 Loop *OuterMostLoop = *(LoopList.begin());
752 OuterMostLoop, DI, SE, ORE)) {
764 <<
"' needs an unique exit block");
768 unsigned SelecLoopId = selectLoopForInterchange(LoopList);
769 CacheCostManager CCM(LoopList[0], AR, DI);
774 for (
unsigned j = SelecLoopId;
j > 0;
j--) {
775 bool ChangedPerIter =
false;
776 for (
unsigned i = SelecLoopId; i > SelecLoopId -
j; i--) {
778 processLoop(LoopList, i, i - 1, DependencyMatrix, CCM);
779 ChangedPerIter |= Interchanged;
790 bool processLoop(SmallVectorImpl<Loop *> &LoopList,
unsigned InnerLoopId,
791 unsigned OuterLoopId,
792 std::vector<std::vector<char>> &DependencyMatrix,
793 CacheCostManager &CCM) {
794 Loop *OuterLoop = LoopList[OuterLoopId];
795 Loop *InnerLoop = LoopList[InnerLoopId];
797 <<
" and OuterLoopId = " << OuterLoopId <<
"\n");
798 LoopInterchangeLegality LIL(Opts, OuterLoop, InnerLoop, SE, ORE, DT);
799 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) {
800 LLVM_DEBUG(
dbgs() <<
"Cannot prove legality, not interchanging loops '"
801 << OuterLoop->
getName() <<
"' and '"
802 << InnerLoop->
getName() <<
"'\n");
807 <<
"' are legal to interchange\n");
808 LoopInterchangeProfitability LIP(Opts, OuterLoop, InnerLoop, SE, ORE);
809 if (!LIP.isProfitable(InnerLoop, OuterLoop, InnerLoopId, OuterLoopId,
810 DependencyMatrix, CCM)) {
812 <<
"' and '" << InnerLoop->
getName()
813 <<
"' not profitable.\n");
818 return OptimizationRemark(
DEBUG_TYPE,
"Interchanged",
821 <<
"Loop interchanged with enclosing loop.";
824 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LIL);
825 LIT.transform(LIL.getHasNoWrapReductions(), LIL.getHasNoInfInsts());
827 << OuterLoop->
getName() <<
"' and inner loop '"
828 << InnerLoop->
getName() <<
"'\n");
834 std::swap(LoopList[OuterLoopId], LoopList[InnerLoopId]);
847bool LoopInterchangeLegality::collectAddressInstsToHoist(
853 if (Visited.
size() > Opts.loop_interchange_max_address_insts_to_hoist ||
854 InnerL->
contains(
I) ||
I->mayReadFromMemory() ||
859 if (!collectAddressInstsToHoist(
Op, InnerL, AddressInsts, Visited))
866bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB,
868 return any_of(*BB, [Skip](
const Instruction &
I) {
871 return I.mayHaveSideEffects() ||
I.mayReadFromMemory();
900 auto IsDirectInnerLoopBlock = [InnerLoop](
BasicBlock *BB) {
903 [BB](
Loop *SubLoop) { return SubLoop->contains(BB); });
909 Worklist.
insert(Condition);
911 for (
PHINode *Induction : InnerLoopInductions) {
913 Induction->getIncomingValueForBlock(InnerLoop->
getLoopLatch()));
914 if (Incoming && !
is_contained(InnerLoopInductions, Incoming))
915 Worklist.
insert(Incoming);
918 for (
unsigned I = 0;
I < Worklist.
size(); ++
I) {
924 if (!OperandI || !IsDirectInnerLoopBlock(OperandI->getParent()) ||
927 Worklist.
insert(OperandI);
933bool LoopInterchangeLegality::tightlyNested(
Loop *OuterLoop,
Loop *InnerLoop) {
939 <<
"' and '" << InnerLoop->
getName()
940 <<
"' are tightly nested\n");
960 for (BasicBlock *Succ :
successors(OuterLoopHeader))
961 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->
getHeader())
964 LLVM_DEBUG(
dbgs() <<
"Checking instructions in Loop header and Loop latch\n");
970 assert(InnerReductions.size() <= 1 &&
971 "So far we only support at most one reduction.");
972 if (InnerReductions.size() == 1)
973 Skip = InnerReductions[0].LcssaStore;
977 if (containsUnsafeInstructions(OuterLoopHeader, Skip) ||
978 containsUnsafeInstructions(OuterLoopLatch, Skip))
984 if (InnerLoopPreHeader != OuterLoopHeader &&
985 containsUnsafeInstructions(InnerLoopPreHeader, Skip))
993 if (&SuccInner != OuterLoopLatch) {
995 <<
" does not lead to the outer loop latch.\n";);
1001 if (containsUnsafeInstructions(InnerLoopExit, Skip))
1009bool LoopInterchangeLegality::isLoopStructureUnderstood() {
1011 for (PHINode *InnerInduction : InnerLoopInductions) {
1012 unsigned Num = InnerInduction->getNumOperands();
1013 for (
unsigned i = 0; i < Num; ++i) {
1014 Value *Val = InnerInduction->getOperand(i);
1024 if (InnerInduction->getIncomingBlock(IncomBlockIndx) ==
1025 InnerLoopPreheader &&
1039 CondBrInst *InnerLoopLatchBI =
1041 if (!InnerLoopLatchBI)
1060 std::function<bool(
Value *)> IsPathToInnerIndVar;
1061 IsPathToInnerIndVar = [
this, &IsPathToInnerIndVar](
const Value *
V) ->
bool {
1070 return IsPathToInnerIndVar(
I->getOperand(0));
1072 return IsPathToInnerIndVar(
I->getOperand(0)) &&
1073 IsPathToInnerIndVar(
I->getOperand(1));
1079 if (IsPathToInnerIndVar(Op0) && IsPathToInnerIndVar(Op1))
1087 }
else if (IsPathToInnerIndVar(Op1) && !
isa<Constant>(Op1)) {
1092 if (
Left ==
nullptr)
1109 if (
PHI->getNumIncomingValues() != 1)
1197 assert(
I->getOpcode() == OpCode &&
1198 "Expected the instruction to be the reduction operation");
1203 if (
I->hasNoSignedWrap() ||
I->hasNoUnsignedWrap())
1227 if (
PHI->getNumIncomingValues() == 1)
1240bool LoopInterchangeLegality::isInnerReduction(
1241 Loop *L, PHINode *Phi, SmallVectorImpl<Instruction *> &HasNoWrapInsts) {
1245 if (!
L->isInnermost()) {
1246 LLVM_DEBUG(
dbgs() <<
"Only supported when the loop is the innermost.\n");
1248 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1249 L->getStartLoc(),
L->getHeader())
1250 <<
"Only supported when the loop is the innermost.";
1255 if (
Phi->getNumIncomingValues() != 2)
1258 Value *Init =
Phi->getIncomingValueForBlock(
L->getLoopPreheader());
1259 Value *
Next =
Phi->getIncomingValueForBlock(
L->getLoopLatch());
1265 <<
"Only supported for the reduction with a constant initial value.\n");
1267 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1268 L->getStartLoc(),
L->getHeader())
1269 <<
"Only supported for the reduction with a constant initial "
1278 if (!
L->contains(BB))
1283 if (!
Phi->hasOneUser())
1295 PHINode *Lcssa = NULL;
1296 for (
auto *U :
Next->users()) {
1301 if (Lcssa == NULL &&
P->getParent() == ExitBlock &&
1302 P->getIncomingValueForBlock(
L->getLoopLatch()) ==
Next)
1313 LLVM_DEBUG(
dbgs() <<
"Only supported when the reduction is used once in "
1314 "the outer loop.\n");
1316 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1317 L->getStartLoc(),
L->getHeader())
1318 <<
"Only supported when the reduction is used once in the outer "
1324 StoreInst *LcssaStore =
1326 if (!LcssaStore || LcssaStore->
getParent() != ExitBlock)
1338 SmallVector<Instruction *, 4> AddressInstsToHoist;
1339 SmallPtrSet<Instruction *, 8> Visited;
1340 if (!collectAddressInstsToHoist(MemRef, L, AddressInstsToHoist, Visited)) {
1341 LLVM_DEBUG(
dbgs() <<
"Only supported when the memory reference can be "
1342 "computed before the inner loop.\n");
1344 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1345 L->getStartLoc(),
L->getHeader())
1346 <<
"Only supported when the memory reference can be computed "
1347 "before the inner loop.";
1357 SR.LcssaPhi = Lcssa;
1358 SR.LcssaStore = LcssaStore;
1361 SR.AddressInstsToHoist = std::move(AddressInstsToHoist);
1363 InnerReductions.push_back(SR);
1367bool LoopInterchangeLegality::checkInductionsAndReductions(
Loop *OuterLoop) {
1368 auto ChildLoop = [](
Loop *
L) {
1369 assert(
L->getSubLoops().size() <= 1 &&
1370 "Expect at most one child loop for now.");
1371 return L->getSubLoops().empty() ? nullptr :
L->getSubLoops().front();
1374 Loop *InnerLoop = ChildLoop(OuterLoop);
1375 for (
Loop *CurLoop = OuterLoop; CurLoop; CurLoop = ChildLoop(CurLoop)) {
1376 for (PHINode &
PHI : CurLoop->getHeader()->phis()) {
1377 InductionDescriptor
ID;
1379 if (CurLoop == InnerLoop) {
1380 const SCEV *Step =
ID.getStep();
1383 InnerLoopInductions.push_back(&
PHI);
1388 if (CurLoop == OuterLoop) {
1390 if (
PHI.getNumIncomingValues() != 2) {
1391 LLVM_DEBUG(
dbgs() <<
"Only PHI nodes in the outer loop header with 2 "
1392 "incoming values are supported.\n");
1400 InnerLoop,
V, HasNoWrapReductions, HasNoInfInsts);
1420 [InnerRedPhi](User *U) { return U == InnerRedPhi; })) {
1423 <<
"Failed to recognize PHI as an induction or reduction.\n");
1425 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIOuter",
1428 <<
"Only outer loops with induction or reduction PHI nodes "
1429 "can be interchanged currently.";
1434 OuterInnerReductions.insert(&
PHI);
1435 OuterInnerReductions.insert(InnerRedPhi);
1437 if (OuterInnerReductions.count(&
PHI)) {
1438 LLVM_DEBUG(
dbgs() <<
"Found a reduction across the outer loop.\n");
1439 }
else if (Opts.loop_interchange_reduction_to_mem &&
1440 isInnerReduction(CurLoop, &
PHI, HasNoWrapReductions)) {
1445 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedPHIInner",
1446 CurLoop->getStartLoc(),
1447 CurLoop->getHeader())
1448 <<
"Only inner loops with induction or reduction PHI nodes "
1449 "can be interchanged currently.";
1457 if (InnerReductions.size() > 1) {
1460 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerReduction",
1461 CurLoop->getStartLoc(),
1462 CurLoop->getHeader())
1463 <<
"Only supports at most one reduction.";
1469 return !InnerLoopInductions.empty();
1474bool LoopInterchangeLegality::currentLimitations() {
1484 dbgs() <<
"Loops where the latch is not the exiting block are not"
1485 <<
" supported currently.\n");
1487 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ExitingNotLatch",
1490 <<
"Loops where the latch is not the exiting block cannot be"
1491 " interchange currently.";
1497 if (!isLoopStructureUnderstood()) {
1500 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedStructureInner",
1503 <<
"Inner loop structure not understood currently.";
1510 for (
Loop *L : {OuterLoop, InnerLoop}) {
1513 if (
L->contains(
Pred))
1517 dbgs() <<
"Indirect branch found in the loop predecessor.\n");
1519 return OptimizationRemarkMissed(
DEBUG_TYPE,
"IndirectBranchPreheader",
1520 L->getStartLoc(),
L->getHeader())
1521 <<
"Indirect branch found in the loop predecessor.";
1530 SmallPtrSet<BasicBlock *, 2> InnerLoopHeaderSuccs;
1532 if (!InnerLoopHeaderSuccs.
insert(Succ).second)
1555 if (
PHI.getNumIncomingValues() > 1)
1559 if (&
PHI == LcssaReduction)
1562 PHINode *PN = dyn_cast<PHINode>(U);
1565 if (Reductions.count(PN))
1567 BasicBlock *PB = PN->getParent();
1568 if (!OuterL->contains(PB))
1570 return PB != OuterL->getLoopLatch();
1587 for (
Value *Incoming :
PHI.incoming_values()) {
1628 for (
PHINode *InductionPHI : InductionPHIs) {
1630 InductionPHI->getIncomingValueForBlock(InnerLoopLatch)))
1632 Worklist.
insert(IncomingI);
1638 InductionPHIs.
end());
1639 for (
unsigned I = 0;
I < Worklist.
size(); ++
I) {
1651bool LoopInterchangeLegality::canInterchangeLoops(
unsigned InnerLoopId,
1652 unsigned OuterLoopId,
1653 CharMatrix &DepMatrix) {
1655 LLVM_DEBUG(
dbgs() <<
"Failed interchange InnerLoopId = " << InnerLoopId
1656 <<
" and OuterLoopId = " << OuterLoopId
1657 <<
" due to dependence\n");
1659 return OptimizationRemarkMissed(
DEBUG_TYPE,
"Dependence",
1662 <<
"Cannot interchange loops due to dependences.";
1667 for (
auto *BB : OuterLoop->
blocks())
1668 for (Instruction &
I : *BB) {
1675 if (!
I.mayHaveSideEffects() && !
I.mayReadFromMemory())
1680 <<
"Loops contain instructions that cannot be safely interchanged\n");
1682 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsafeInst",
1683 I.getDebugLoc(),
I.getParent())
1684 <<
"Cannot interchange loops due to instruction that is "
1685 "potentially unsafe to interchange.";
1691 if (!checkInductionsAndReductions(OuterLoop)) {
1692 LLVM_DEBUG(
dbgs() <<
"Failed to find inner loop inductions or found "
1693 "unsupported reductions.\n");
1698 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop latch.\n");
1700 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedInnerLatchPHI",
1703 <<
"Cannot interchange loops because unsupported PHI nodes found "
1704 "in inner loop latch.";
1713 LLVM_DEBUG(
dbgs() <<
"Interchange would re-nest or duplicate freeze\n");
1715 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsafeInst",
1718 <<
"Cannot interchange loops because re-nesting or duplicating "
1719 "freeze may change its sampling behavior.";
1726 if (currentLimitations()) {
1727 LLVM_DEBUG(
dbgs() <<
"Not legal because of current transform limitation\n");
1732 if (!tightlyNested(OuterLoop, InnerLoop)) {
1735 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotTightlyNested",
1738 <<
"Cannot interchange loops because they are not tightly "
1746 PHINode *LcssaReduction =
nullptr;
1747 assert(InnerReductions.size() <= 1 &&
1748 "So far we only support at most one reduction.");
1749 if (InnerReductions.size() == 1)
1750 LcssaReduction = InnerReductions[0].LcssaPhi;
1754 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in inner loop exit.\n");
1756 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1759 <<
"Found unsupported PHI node in loop exit.";
1765 LLVM_DEBUG(
dbgs() <<
"Found unsupported PHI nodes in outer loop exit.\n");
1767 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedExitPHI",
1770 <<
"Found unsupported PHI node in loop exit.";
1776 [](PHINode &
PHI) { return PHI.getNumIncomingValues() != 1; })) {
1777 LLVM_DEBUG(
dbgs() <<
"Only outer loop latch PHI nodes with one incoming "
1778 "value are supported.\n");
1780 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedLatchPHI",
1783 <<
"Only outer loop latch PHI nodes with one incoming value are "
1797 if (
any_of(
PHI.users(), [](
const User *U) { return !isa<PHINode>(U); })) {
1798 LLVM_DEBUG(
dbgs() <<
"Outer loop latch PHI has a non-PHI user.\n");
1800 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnsupportedLatchPHI",
1803 <<
"Cannot interchange loops because an outer loop latch PHI "
1804 "node has a non-PHI user.";
1812void CacheCostManager::computeIfUnitinialized() {
1827 for (
const auto &[Idx,
Cost] :
enumerate((*CC)->getLoopCosts()))
1831CacheCost *CacheCostManager::getCacheCost() {
1832 computeIfUnitinialized();
1836const DenseMap<const Loop *, unsigned> &CacheCostManager::getCostMap() {
1837 computeIfUnitinialized();
1847static std::optional<const SCEV *>
1853 return std::nullopt;
1858 return std::nullopt;
1861 std::optional<const SCEV *> Coeff =
1863 if (!Coeff.has_value())
1864 return std::nullopt;
1867 assert(!*Coeff &&
"Found more than one addrec for the same loop");
1873int LoopInterchangeProfitability::getInstrOrderCost() {
1874 SmallPtrSet<const SCEV *, 4> GoodBasePtrs, BadBasePtrs;
1875 for (BasicBlock *BB : InnerLoop->
blocks()) {
1876 for (Instruction &Ins : *BB) {
1881 std::optional<const SCEV *> OuterCoeff =
1883 std::optional<const SCEV *> InnerCoeff =
1886 if (!OuterCoeff.has_value() || !*OuterCoeff || !InnerCoeff.has_value() ||
1896 const SCEV *OuterStep = SE->
getAbsExpr(*OuterCoeff,
false);
1897 const SCEV *InnerStep = SE->
getAbsExpr(*InnerCoeff,
false);
1917 GoodBasePtrs.
insert(BasePtr);
1919 BadBasePtrs.
insert(BasePtr);
1923 int GoodOrder = GoodBasePtrs.
size();
1924 int BadOrder = BadBasePtrs.
size();
1925 return GoodOrder - BadOrder;
1929LoopInterchangeProfitability::isProfitablePerLoopCacheAnalysis(
1930 const DenseMap<const Loop *, unsigned> &CostMap, CacheCost *
CC) {
1934 auto InnerLoopIt = CostMap.
find(InnerLoop);
1935 if (InnerLoopIt == CostMap.
end())
1936 return std::nullopt;
1937 auto OuterLoopIt = CostMap.
find(OuterLoop);
1938 if (OuterLoopIt == CostMap.
end())
1939 return std::nullopt;
1941 if (
CC->getLoopCost(*OuterLoop) ==
CC->getLoopCost(*InnerLoop))
1942 return std::nullopt;
1943 unsigned InnerIndex = InnerLoopIt->second;
1944 unsigned OuterIndex = OuterLoopIt->second;
1946 <<
", OuterIndex = " << OuterIndex <<
"\n");
1947 assert(InnerIndex != OuterIndex &&
"CostMap should assign unique "
1948 "numbers to each loop");
1949 return std::optional<bool>(InnerIndex < OuterIndex);
1953LoopInterchangeProfitability::isProfitablePerInstrOrderCost() {
1957 int Cost = getInstrOrderCost();
1959 if (
Cost < 0 &&
Cost < Opts.loop_interchange_threshold)
1960 return std::optional<bool>(
true);
1962 return std::nullopt;
1967 for (
const auto &Dep : DepMatrix) {
1968 char Dir = Dep[LoopId];
1969 char DepType = Dep.back();
1970 assert((DepType ==
'<' || DepType ==
'*') &&
1971 "Unexpected element in dependency vector");
1974 if (Dir ==
'=' || Dir ==
'I')
1980 if (Dir ==
'<' && DepType ==
'<')
1989std::optional<bool> LoopInterchangeProfitability::isProfitableForVectorization(
1990 unsigned InnerLoopId,
unsigned OuterLoopId, CharMatrix &DepMatrix) {
2006 return std::nullopt;
2009bool LoopInterchangeProfitability::isProfitable(
2010 const Loop *InnerLoop,
const Loop *OuterLoop,
unsigned InnerLoopId,
2011 unsigned OuterLoopId, CharMatrix &DepMatrix, CacheCostManager &CCM) {
2020 if (InnerBTC && InnerBTC->
isZero()) {
2021 LLVM_DEBUG(
dbgs() <<
"Inner loop back-edge isn't taken, rejecting "
2022 "single iteration loop\n");
2025 if (OuterBTC && OuterBTC->
isZero()) {
2026 LLVM_DEBUG(
dbgs() <<
"Outer loop back-edge isn't taken, rejecting "
2027 "single iteration loop\n");
2032 Opts.loop_interchange_profitabilities;
2033 if (Profitabilities.
empty())
2037 if (Profitabilities.
size() == 1 &&
2038 Profitabilities[0] == LoopInterchangeRule::Ignore)
2041 "Duplicate rules and option 'ignore' are not allowed");
2051 std::optional<bool> shouldInterchange;
2054 case LoopInterchangeRule::PerLoopCacheAnalysis: {
2055 CacheCost *
CC = CCM.getCacheCost();
2056 const DenseMap<const Loop *, unsigned> &CostMap = CCM.getCostMap();
2057 shouldInterchange = isProfitablePerLoopCacheAnalysis(CostMap,
CC);
2060 case LoopInterchangeRule::PerInstrOrderCost:
2061 shouldInterchange = isProfitablePerInstrOrderCost();
2063 case LoopInterchangeRule::ForVectorization:
2065 isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix);
2067 case LoopInterchangeRule::Ignore:
2074 if (shouldInterchange.has_value())
2078 if (!shouldInterchange.has_value()) {
2080 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
2083 <<
"Insufficient information to calculate the cost of loop for "
2087 }
else if (!shouldInterchange.value()) {
2089 return OptimizationRemarkMissed(
DEBUG_TYPE,
"InterchangeNotProfitable",
2092 <<
"Interchanging loops is not considered to improve cache "
2093 "locality nor vectorization.";
2100void LoopInterchangeTransform::removeChildLoop(
Loop *OuterLoop,
2102 for (
Loop *L : *OuterLoop)
2103 if (L == InnerLoop) {
2104 OuterLoop->removeChildLoop(L);
2133void LoopInterchangeTransform::restructureLoops(
2134 Loop *NewInner,
Loop *NewOuter, BasicBlock *OrigInnerPreHeader,
2135 BasicBlock *OrigOuterPreHeader) {
2136 Loop *OuterLoopParent = OuterLoop->getParentLoop();
2143 removeChildLoop(NewInner, NewOuter);
2152 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->
blocks());
2156 for (BasicBlock *BB : NewInner->
blocks())
2164 for (BasicBlock *BB : OrigInnerBBs) {
2169 if (BB == OuterHeader || BB == OuterLatch)
2207void LoopInterchangeTransform::reduction2Memory() {
2209 LIL.getInnerReductions();
2212 "So far we only support at most one reduction.");
2214 LoopInterchangeLegality::InnerReduction SR = InnerReductions[0];
2219 for (Instruction *
I : SR.AddressInstsToHoist) {
2221 I->moveBefore(InsertPt);
2229 PHINode *FirstIter =
2230 Builder.CreatePHI(Type::getInt1Ty(
Context), 2,
"first.iter");
2235 assert(FirstIter->
isComplete() &&
"The FirstIter PHI node is not complete.");
2240 Instruction *LoadMem = Builder.CreateLoad(SR.ElemTy, SR.MemRef);
2243 Value *NewVar = Builder.CreateSelect(FirstIter, SR.Init, LoadMem,
"new.var");
2254void LoopInterchangeTransform::transform(
2255 ArrayRef<Instruction *> DropNoWrapInsts,
2256 ArrayRef<Instruction *> DropNoInfInsts) {
2259 LIL.getInnerReductions();
2260 if (InnerReductions.
size() == 1)
2264 auto &InductionPHIs = LIL.getInnerLoopInductions();
2265 assert(!InductionPHIs.empty() &&
2266 "Expected at least one induction variable in the inner loop");
2268 SmallVector<Instruction *, 8> InnerIndexVarList;
2269 for (PHINode *CurInductionPHI : InductionPHIs) {
2271 CurInductionPHI->getIncomingValueForBlock(InnerLoop->
getLoopLatch()));
2273 "Incoming value from loop latch isn't an instruction");
2276 InnerIndexVarList.
push_back(IncomingValue);
2289 SmallSetVector<Instruction *, 4> WorkList;
2291 auto MoveInstructions = [&i, &WorkList,
this, &InductionPHIs, NewLatch]() {
2292 for (; i < WorkList.
size(); i++) {
2296 "MoveInstructions does not support PHI nodes");
2302 "Moving instructions with side-effects may change behavior of "
2313 for (
Value *
Op : WorkList[i]->operands()) {
2330 for (Instruction *InnerIndexVar : InnerIndexVarList)
2345 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2347 if (InnerLoopPreHeader != OuterLoopHeader) {
2351 "Expected equivalent incoming values in inner loop preheader");
2352 P.replaceAllUsesWith(
P.getIncomingValue(0));
2353 P.eraseFromParent();
2355 for (Instruction &
I :
2357 std::prev(InnerLoopPreHeader->
end()))))
2361 adjustLoopBranches();
2365 for (Instruction *
Reduction : DropNoWrapInsts) {
2369 for (Instruction *
I : DropNoInfInsts)
2370 I->setHasNoInfs(
false);
2389 I->removeFromParent();
2404 std::vector<DominatorTree::UpdateType> &DTUpdates,
2405 bool MustUpdateOnce =
true) {
2407 "BI must jump to OldBB exactly once.");
2409 for (
Use &
Op : Term->operands())
2416 DTUpdates.push_back(
2417 {DominatorTree::UpdateKind::Insert, Term->getParent(), NewBB});
2418 DTUpdates.push_back(
2419 {DominatorTree::UpdateKind::Delete, Term->getParent(), OldBB});
2438 assert(
P.getNumIncomingValues() == 1 &&
2439 "Only loops with a single exit are supported!");
2441 Value *IncomingValue =
P.getIncomingValueForBlock(InnerLatch);
2448 "Expected non-instruction incoming value to be loop invariant");
2449 P.replaceAllUsesWith(IncomingValue);
2450 P.eraseFromParent();
2461 if (!IncIInnerMost || (IncIInnerMost->getParent() != InnerLatch &&
2462 IncIInnerMost->
getParent() != InnerHeader))
2466 [OuterHeader, OuterExit, IncI, InnerHeader](
User *U) {
2467 return (cast<PHINode>(U)->getParent() == OuterHeader &&
2468 IncI->getParent() == InnerHeader) ||
2469 cast<PHINode>(U)->getParent() == OuterExit;
2471 "Can only replace phis iff the uses are in the loop nest exit or "
2472 "the incoming value is defined in the inner header (it will "
2473 "dominate all loop blocks after interchanging)");
2474 P.replaceAllUsesWith(IncI);
2475 P.eraseFromParent();
2503 if (
P.getNumIncomingValues() != 1)
2517 if (
Pred == OuterLatch)
2522 P.setIncomingValue(0, NewPhi);
2562 if (OuterLoopLatch == InnerLoopExit)
2569 assert(Phi->getNumIncomingValues() == 1 &&
"Single input phi expected");
2570 LLVM_DEBUG(
dbgs() <<
"Removing 1-input phi in non-exit block: " << *Phi
2572 Phi->replaceAllUsesWith(Phi->getIncomingValue(0));
2573 Phi->eraseFromParent();
2577void LoopInterchangeTransform::adjustLoopBranches() {
2579 std::vector<DominatorTree::UpdateType> DTUpdates;
2581 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
2584 assert(OuterLoopPreHeader != OuterLoop->getHeader() &&
2585 InnerLoopPreHeader != InnerLoop->
getHeader() && OuterLoopPreHeader &&
2586 InnerLoopPreHeader &&
"Guaranteed by loop-simplify form");
2596 OuterLoopPreHeader =
2598 if (InnerLoopPreHeader == OuterLoop->getHeader())
2599 InnerLoopPreHeader =
2604 BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
2606 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
2613 CondBrInst *OuterLoopLatchBI =
2615 CondBrInst *InnerLoopLatchBI =
2620 assert(OuterLoopPredecessor && InnerLoopLatchPredecessor &&
2621 "Failed to find a unique predecessor");
2622 assert(OuterLoopLatchBI && InnerLoopLatchBI &&
2623 "Failed to find a conditional branch");
2630 assert(InnerLoopHeaderSuccessor &&
2631 "Failed to find a unique successor for the inner loop header");
2638 InnerLoopPreHeader, DTUpdates,
false);
2648 InnerLoopHeaderSuccessor, DTUpdates,
2656 OuterLoopPreHeader, DTUpdates);
2659 if (InnerLoopLatchBI->
getSuccessor(0) == InnerLoopHeader)
2660 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(1);
2662 InnerLoopLatchSuccessor = InnerLoopLatchBI->
getSuccessor(0);
2665 InnerLoopLatchSuccessor, DTUpdates);
2667 if (OuterLoopLatchBI->
getSuccessor(0) == OuterLoopHeader)
2668 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(1);
2670 OuterLoopLatchSuccessor = OuterLoopLatchBI->
getSuccessor(0);
2673 OuterLoopLatchSuccessor, DTUpdates);
2674 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch,
2678 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader,
2679 OuterLoopPreHeader);
2681 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch,
2682 OuterLoopHeader, OuterLoopLatch, InnerLoop->
getExitBlock(),
2688 auto &OuterInnerReductions = LIL.getOuterInnerReductions();
2691 for (PHINode &
PHI : InnerLoopHeader->
phis())
2692 if (OuterInnerReductions.contains(&
PHI))
2695 for (PHINode &
PHI : OuterLoopHeader->
phis())
2696 if (OuterInnerReductions.contains(&
PHI))
2702 for (PHINode *
PHI : OuterLoopPHIs) {
2705 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2707 for (PHINode *
PHI : InnerLoopPHIs) {
2710 assert(OuterInnerReductions.count(
PHI) &&
"Expected a reduction PHI node");
2729 SmallVector<Instruction *, 4> MayNeedLCSSAPhis;
2730 for (Instruction &
I :
2736 "LoopInterchange handed dominance-broken IR to LCSSA rebuild");
2754 <<
"Computed dependence info, invoking the transform.";
2759 if (!LoopInterchange(Opts, &AR.
SE, &AR.
LI, &DI, &AR.
DT, &AR, &ORE).run(LN))
2761 U.markLoopNestChanged(
true);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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
constexpr LoopInterchangeRule DefaultProfitabilities[]
static FreezeInst * findFreezeInInnerLatchCloneSet(Loop *InnerLoop, ArrayRef< PHINode * > InnerLoopInductions)
static void updateSuccessor(Instruction *Term, BasicBlock *OldBB, BasicBlock *NewBB, std::vector< DominatorTree::UpdateType > &DTUpdates, bool MustUpdateOnce=true)
static bool areInnerLoopLatchPHIsSupported(Loop *InnerLoop, ArrayRef< PHINode * > InductionPHIs)
The transform partially clones the inner loop's latch block, but PHI nodes cannot be cloned this way.
static bool isComputableLoopNest(ScalarEvolution *SE, ArrayRef< Loop * > LoopList)
static bool areOuterLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop)
static FreezeInst * findFreezeInReNestedBlocks(Loop *OuterLoop, Loop *InnerLoop)
static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore)
Move all instructions except the terminator from FromBB right before InsertBefore.
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 bool populateDependencyMatrix(const ScalarOptions &Opts, CharMatrix &DepMatrix, unsigned Level, Loop *L, DependenceInfo *DI, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
static bool hasSupportedLoopDepth(const ScalarOptions &Opts, ArrayRef< Loop * > LoopList, OptimizationRemarkEmitter &ORE)
static void printDepMatrix(CharMatrix &DepMatrix)
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 bool inThisOrder(const Instruction *Src, const Instruction *Dst)
Return true if Src appears before Dst in the same basic block.
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 bool noDuplicateRulesAndIgnore(ArrayRef< LoopInterchangeRule > Rules)
static Value * followLCSSA(Value *SV)
static void populateWorklist(Loop &L, LoopVector &LoopList)
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 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.
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
static bool processLoop(Loop &L, const AArch64Subtarget &ST, DataLayout DL)
SmallVector< Value *, 8 > ValueVector
This file defines the SmallSet class.
This file defines the SmallVector class.
static bool isProfitable(const CGDataOptions &Opts, 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.
bool empty() const
Check if the array is empty.
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.
InstListType::iterator iterator
Instruction iterators...
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.
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.
This class represents a freeze function that returns random concrete value if an operand is either a ...
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.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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 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.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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 replaceLoop(LoopT *Old, LoopT *New)
Replace a loop among its siblings (a parent loop's child list or the top-level list) with a new 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.
LLVM_ABI DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
LLVM_ABI 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.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
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.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
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...
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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.
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.
@ BasicBlock
Various leaf nodes.
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.
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.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
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...
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
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.
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
@ End
Run the machine verifier once, at the end of the pipeline.
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...