70#define DEBUG_TYPE "loop-fusion"
73STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
74STATISTIC(InvalidPreheader,
"Loop has invalid preheader");
76STATISTIC(InvalidExitingBlock,
"Loop has invalid exiting blocks");
77STATISTIC(InvalidExitBlock,
"Loop has invalid exit block");
80STATISTIC(AddressTakenBB,
"Basic block has address taken");
81STATISTIC(MayThrowException,
"Loop may throw an exception");
82STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
83STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
84STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
85STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
86STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
87STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
90 "Loop has a non-empty preheader with instructions that cannot be moved");
91STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
92STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
93STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
94 "instructions that cannot be moved");
95STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
96 "instructions that cannot be moved");
99 "The second candidate is guarded while the first one is not");
100STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
101STATISTIC(NumSunkInsts,
"Number of hoisted preheader instructions.");
106 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
107 "fusion can take place"));
112 cl::desc(
"Enable verbose debugging for Loop Fusion"),
127struct FusionCandidate {
166 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
167 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
168 Latch(L->getLoopLatch()), L(L), Valid(
true),
169 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
170 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
177 if (BB->hasAddressTaken()) {
179 reportInvalidCandidate(AddressTakenBB);
190 if (
SI->isVolatile()) {
197 if (LI->isVolatile()) {
203 if (
I.mayWriteToMemory())
204 MemWrites.push_back(&
I);
205 if (
I.mayReadFromMemory())
206 MemReads.push_back(&
I);
213 return Preheader && Header && ExitingBlock && ExitBlock && Latch &&
L &&
220 assert(!
L->isInvalid() &&
"Loop is invalid!");
221 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
222 assert(Header ==
L->getHeader() &&
"Header is out of sync");
223 assert(ExitingBlock ==
L->getExitingBlock() &&
224 "Exiting Blocks is out of sync");
225 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
226 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
236 return GuardBranch->getParent();
242 void updateAfterPeeling() {
243 Preheader =
L->getLoopPreheader();
244 Header =
L->getHeader();
245 ExitingBlock =
L->getExitingBlock();
246 ExitBlock =
L->getExitBlock();
247 Latch =
L->getLoopLatch();
259 assert(GuardBranch &&
"Only valid on guarded loops.");
267#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
269 dbgs() <<
"\tGuardBranch: ";
271 dbgs() << *GuardBranch;
275 << (GuardBranch ? GuardBranch->getName() :
"nullptr") <<
"\n"
276 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
278 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
280 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
281 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
283 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
285 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
301 ++InvalidExitingBlock;
315 <<
" trip count not computable!\n");
319 if (!
L->isLoopSimplifyForm()) {
321 <<
" is not in simplified form!\n");
325 if (!
L->isRotatedForm()) {
349 L->getStartLoc(),
L->getHeader())
350 <<
"Loop is not a candidate for fusion");
355 L->getStartLoc(),
L->getHeader())
356 <<
"[" <<
L->getHeader()->getParent()->getName() <<
"]: "
357 <<
"Loop is not a candidate for fusion: " << Stat.getDesc());
374 dbgs() <<
"****************************\n";
375 for (
const Loop *L : LV)
377 dbgs() <<
"****************************\n";
382 OS << FC.Preheader->getName();
391 for (
const FusionCandidate &FC : CandList)
399 dbgs() <<
"Fusion Candidates: \n";
400 for (
const auto &CandidateList : FusionCandidates) {
401 dbgs() <<
"*** Fusion Candidate List ***\n";
402 dbgs() << CandidateList;
403 dbgs() <<
"****************************\n";
416struct LoopDepthTree {
417 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
421 LoopDepthTree(LoopInfo &LI) : Depth(1) {
428 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
432 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
436 LoopsOnLevelTy LoopsOnNextLevel;
440 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
441 LoopsOnNextLevel.emplace_back(
LoopVector(
L->begin(),
L->end()));
443 LoopsOnLevel = LoopsOnNextLevel;
444 RemovedLoops.clear();
448 bool empty()
const {
return size() == 0; }
449 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
450 unsigned getDepth()
const {
return Depth; }
452 iterator
begin() {
return LoopsOnLevel.begin(); }
453 iterator
end() {
return LoopsOnLevel.end(); }
454 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
455 const_iterator
end()
const {
return LoopsOnLevel.end(); }
460 SmallPtrSet<const Loop *, 8> RemovedLoops;
466 LoopsOnLevelTy LoopsOnLevel;
481 PostDominatorTree &PDT;
482 OptimizationRemarkEmitter &ORE;
484 const TargetTransformInfo &TTI;
487 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
488 ScalarEvolution &SE, PostDominatorTree &PDT,
489 OptimizationRemarkEmitter &ORE,
const DataLayout &
DL,
490 AssumptionCache &AC,
const TargetTransformInfo &TTI)
491 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
492 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
497 bool fuseLoops(Function &
F) {
504 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
508 while (!LDT.empty()) {
509 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
510 << LDT.getDepth() <<
"\n";);
513 assert(LV.size() > 0 &&
"Empty loop set was build!");
522 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
528 collectFusionCandidates(LV);
533 FusionCandidates.clear();
559 void collectFusionCandidates(
const LoopVector &LV) {
563 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
564 if (!CurrCand.isEligibleForFusion(SE))
572 bool FoundAdjacent =
false;
573 for (
auto &CurrCandList : FusionCandidates) {
574 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
575 CurrCandList.push_back(CurrCand);
576 FoundAdjacent =
true;
577 NumFusionCandidates++;
581 <<
" to existing candidate list\n");
586 if (!FoundAdjacent) {
593 NewCandList.push_back(CurrCand);
594 FusionCandidates.push_back(NewCandList);
604 bool isBeneficialFusion(
const FusionCandidate &FC0,
605 const FusionCandidate &FC1) {
617 std::pair<bool, std::optional<unsigned>>
618 haveIdenticalTripCounts(
const FusionCandidate &FC0,
619 const FusionCandidate &FC1)
const {
620 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
622 UncomputableTripCount++;
623 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
624 return {
false, std::nullopt};
627 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
629 UncomputableTripCount++;
630 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
631 return {
false, std::nullopt};
635 << *TripCount1 <<
" are "
636 << (TripCount0 == TripCount1 ?
"identical" :
"different")
639 if (TripCount0 == TripCount1)
643 "determining the difference between trip counts\n");
647 const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
648 const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
652 if (TC0 == 0 || TC1 == 0) {
653 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
654 "have a constant number of iterations. Peeling "
655 "is not benefical\n");
656 return {
false, std::nullopt};
659 std::optional<unsigned> Difference;
660 int Diff = TC0 - TC1;
666 dbgs() <<
"Difference is less than 0. FC1 (second loop) has more "
667 "iterations than the first one. Currently not supported\n");
670 LLVM_DEBUG(
dbgs() <<
"Difference in loop trip count is: " << Difference
673 return {
false, Difference};
676 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
677 unsigned PeelCount) {
678 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
681 <<
" iterations of the first loop. \n");
684 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
true, VMap);
689 auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
691 assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
692 "Loops should have identical trip counts after peeling");
698 PDT.recalculate(*FC0.Preheader->
getParent());
700 FC0.updateAfterPeeling();
714 SmallVector<Instruction *, 8> WorkList;
716 if (Pred != FC0.ExitBlock) {
719 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
724 for (Instruction *CurrentBranch : WorkList) {
725 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
727 Succ = CurrentBranch->getSuccessor(1);
731 DTU.applyUpdates(TreeUpdates);
736 <<
" iterations from the first loop.\n"
737 "Both Loops have the same number of iterations now.\n");
747 bool fuseCandidates() {
750 for (
auto &CandidateList : FusionCandidates) {
751 if (CandidateList.size() < 2)
755 << CandidateList <<
"\n");
757 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
758 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
763 assert(!LDT.isRemovedLoop(FC0.L) &&
764 "Should not have removed loops in CandidateList!");
765 assert(!LDT.isRemovedLoop(FC1.L) &&
766 "Should not have removed loops in CandidateList!");
768 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
769 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
779 std::pair<bool, std::optional<unsigned>> IdenticalTripCountRes =
780 haveIdenticalTripCounts(FC0, FC1);
781 bool SameTripCount = IdenticalTripCountRes.first;
782 std::optional<unsigned> TCDifference = IdenticalTripCountRes.second;
786 if (FC0.AbleToPeel && !SameTripCount && TCDifference) {
789 <<
"Difference in loop trip counts: " << *TCDifference
790 <<
" is greater than maximum peel count specificed: "
795 SameTripCount =
true;
799 if (!SameTripCount) {
800 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
801 "counts. Not fusing.\n");
802 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
807 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
808 (FC0.GuardBranch && !FC1.GuardBranch)) {
810 "another one is not. Not fusing.\n");
811 reportLoopFusion<OptimizationRemarkMissed>(
812 FC0, FC1, OnlySecondCandidateIsGuarded);
818 if (FC0.GuardBranch && FC1.GuardBranch &&
819 !haveIdenticalGuards(FC0, FC1) && !TCDifference) {
821 "guards. Not Fusing.\n");
822 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
827 if (FC0.GuardBranch) {
828 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
834 "instructions in exit block. Not fusing.\n");
835 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
841 *FC1.GuardBranch->getParent(),
842 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
845 "instructions in guard block. Not fusing.\n");
846 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
854 if (!dependencesAllowFusion(FC0, FC1)) {
855 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
856 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
857 InvalidDependencies);
864 SmallVector<Instruction *, 4> SafeToHoist;
865 SmallVector<Instruction *, 4> SafeToSink;
869 if (!isEmptyPreheader(FC1)) {
875 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
878 "Fusion Candidate Pre-header.\n"
880 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
886 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
888 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
889 if (!BeneficialToFuse) {
890 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
891 FusionNotBeneficial);
899 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
901 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
904 FusionCandidate FC0Copy = FC0;
907 bool Peel = TCDifference && *TCDifference > 0;
909 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
915 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
918 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
919 DT, &PDT, ORE, FC0Copy.PP);
921 assert(FusedCand.isEligibleForFusion(SE) &&
922 "Fused candidate should be eligible for fusion!");
925 LDT.removeLoop(FC1.L);
928 It = CandidateList.erase(It);
929 It = CandidateList.erase(It);
930 It = CandidateList.insert(It, FusedCand);
935 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
949 bool canHoistInst(Instruction &
I,
950 const SmallVector<Instruction *, 4> &SafeToHoist,
951 const SmallVector<Instruction *, 4> &NotHoisting,
952 const FusionCandidate &FC0)
const {
954 assert(FC0PreheaderTarget &&
955 "Expected single successor for loop preheader.");
957 for (Use &
Op :
I.operands()) {
962 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
974 if (!
I.mayReadOrWriteMemory())
977 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
978 for (Instruction *NotHoistedInst : NotHoisting) {
979 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
982 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
984 "preheader that is not being hoisted.\n");
990 for (Instruction *ReadInst : FC0.MemReads) {
991 if (
auto D = DI.depends(ReadInst, &
I)) {
994 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
1000 for (Instruction *WriteInst : FC0.MemWrites) {
1001 if (
auto D = DI.depends(WriteInst, &
I)) {
1003 if (
D->isFlow() ||
D->isOutput()) {
1004 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1015 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1016 for (User *U :
I.users()) {
1029 if (!
I.mayReadOrWriteMemory())
1032 for (Instruction *ReadInst : FC1.MemReads) {
1033 if (
auto D = DI.depends(&
I, ReadInst)) {
1036 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1042 for (Instruction *WriteInst : FC1.MemWrites) {
1043 if (
auto D = DI.depends(&
I, WriteInst)) {
1045 if (
D->isOutput() ||
D->isAnti()) {
1046 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1057 bool collectMovablePreheaderInsts(
1058 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1059 SmallVector<Instruction *, 4> &SafeToHoist,
1060 SmallVector<Instruction *, 4> &SafeToSink)
const {
1064 SmallVector<Instruction *, 4> NotHoisting;
1066 for (Instruction &
I : *FC1Preheader) {
1068 if (&
I == FC1Preheader->getTerminator())
1074 if (
I.mayThrow() || !
I.willReturn()) {
1075 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1081 if (
I.isAtomic() ||
I.isVolatile()) {
1083 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1087 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1094 if (canSinkInst(
I, FC1)) {
1104 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1110 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1111 const FusionCandidate &FC1, Instruction &I0,
1115 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1118 auto DepResult = DI.depends(&I0, &I1);
1124 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1125 << (DepResult->isOrdered() ?
"true" :
"false")
1127 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1131 unsigned Levels = DepResult->getLevels();
1132 unsigned SameSDLevels = DepResult->getSameSDLevels();
1136 if (CurLoopLevel > Levels + SameSDLevels)
1140 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1142 unsigned Direction = DepResult->getDirection(Level,
false);
1148 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1155 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1157 if (DepResult->isScalar(CurLoopLevel,
true) && !DepResult->isAnti()) {
1158 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to a loop-invariant non-anti "
1164 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1174 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1180 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1181 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1187 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1188 const FusionCandidate &FC1) {
1189 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1192 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1194 for (Instruction *WriteL0 : FC0.MemWrites) {
1195 for (Instruction *WriteL1 : FC1.MemWrites)
1196 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1199 for (Instruction *ReadL1 : FC1.MemReads)
1200 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1205 for (Instruction *WriteL1 : FC1.MemWrites) {
1206 for (Instruction *WriteL0 : FC0.MemWrites)
1207 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1210 for (Instruction *ReadL0 : FC0.MemReads)
1211 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1218 for (BasicBlock *BB : FC1.L->
blocks())
1219 for (Instruction &
I : *BB)
1220 for (
auto &
Op :
I.operands())
1241 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1242 const FusionCandidate &FC1)
const {
1244 if (FC0.GuardBranch)
1245 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1247 return FC0.ExitBlock == FC1.getEntryBlock();
1250 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1251 return FC.Preheader->size() == 1;
1256 void movePreheaderInsts(
const FusionCandidate &FC0,
1257 const FusionCandidate &FC1,
1258 SmallVector<Instruction *, 4> &HoistInsts,
1259 SmallVector<Instruction *, 4> &SinkInsts)
const {
1262 "Attempting to sink and hoist preheader instructions, but not all "
1263 "the preheader instructions are accounted for.");
1265 NumHoistedInsts += HoistInsts.
size();
1266 NumSunkInsts += SinkInsts.
size();
1269 if (!HoistInsts.
empty())
1270 dbgs() <<
"Hoisting: \n";
1271 for (Instruction *
I : HoistInsts)
1272 dbgs() << *
I <<
"\n";
1273 if (!SinkInsts.
empty())
1274 dbgs() <<
"Sinking: \n";
1275 for (Instruction *
I : SinkInsts)
1276 dbgs() << *
I <<
"\n";
1279 for (Instruction *
I : HoistInsts) {
1280 assert(
I->getParent() == FC1.Preheader);
1281 I->moveBefore(*FC0.Preheader,
1285 for (Instruction *
I :
reverse(SinkInsts)) {
1286 assert(
I->getParent() == FC1.Preheader);
1294 "Expected the sunk PHI node to have 1 incoming value.");
1295 I->replaceAllUsesWith(
I->getOperand(0));
1296 I->eraseFromParent();
1314 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1315 const FusionCandidate &FC1)
const {
1316 assert(FC0.GuardBranch && FC1.GuardBranch &&
1317 "Expecting FC0 and FC1 to be guarded loops.");
1319 if (
auto FC0CmpInst =
1321 if (
auto FC1CmpInst =
1323 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1330 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1332 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1337 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1339 if (FCLatchBranch) {
1341 "Expecting the two successors of FCLatchBranch to be the same");
1342 UncondBrInst *NewBranch =
1350 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1387 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1388 assert(FC0.isValid() && FC1.isValid() &&
1389 "Expecting valid fusion candidates");
1392 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1401 if (FC0.GuardBranch)
1402 return fuseGuardedLoops(FC0, FC1);
1419 if (FC0.ExitingBlock != FC0.Latch)
1420 for (PHINode &
PHI : FC0.Header->
phis())
1451 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1453 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1456 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1462 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1465 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1466 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1472 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1474 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1478 if (SE.isSCEVable(
PHI->getType()))
1479 SE.forgetValue(
PHI);
1480 if (
PHI->hasNUsesOrMore(1))
1483 PHI->eraseFromParent();
1491 for (PHINode *LCPHI : OriginalFC0PHIs) {
1492 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1493 assert(L1LatchBBIdx >= 0 &&
1494 "Expected loop carried value to be rewired at this point!");
1496 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1498 PHINode *L1HeaderPHI =
1505 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1514 simplifyLatchBranch(FC0);
1518 if (FC0.Latch != FC0.ExitingBlock)
1520 DominatorTree::Insert, FC0.Latch, FC1.Header));
1522 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1523 FC0.Latch, FC0.Header));
1524 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1525 FC1.Latch, FC0.Header));
1526 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1527 FC1.Latch, FC1.Header));
1530 DTU.applyUpdates(TreeUpdates);
1532 LI.removeBlock(FC1.Preheader);
1533 DTU.deleteBB(FC1.Preheader);
1535 LI.removeBlock(FC0.ExitBlock);
1536 DTU.deleteBB(FC0.ExitBlock);
1545 SE.forgetLoop(FC1.L);
1546 SE.forgetLoop(FC0.L);
1549 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1550 for (BasicBlock *BB : Blocks) {
1553 if (LI.getLoopFor(BB) != FC1.L)
1555 LI.changeLoopFor(BB, FC0.L);
1558 const auto &ChildLoopIt = FC1.L->
begin();
1559 Loop *ChildLoop = *ChildLoopIt;
1570 SE.forgetBlockAndLoopDispositions();
1574 mergeLatch(FC0, FC1);
1578 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1601 template <
typename RemarkKind>
1602 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1604 assert(FC0.Preheader && FC1.Preheader &&
1605 "Expecting valid fusion candidates");
1606 using namespace ore;
1607#if LLVM_ENABLE_STATS
1612 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName()))
1613 <<
" and " <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName()))
1614 <<
": " << Stat.getDesc());
1633 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1634 const FusionCandidate &FC1) {
1635 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1637 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1638 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1639 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1640 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1648 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1655 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1668 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1670 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1674 FC1.GuardBranch->eraseFromParent();
1675 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1678 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1680 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1682 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1684 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1688 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1691 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1693 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1694 FC0ExitBlockSuccessor);
1698 "Expecting guard block to have no predecessors");
1700 "Expecting guard block to have no successors");
1715 if (FC0.ExitingBlock != FC0.Latch)
1716 for (PHINode &
PHI : FC0.Header->
phis())
1719 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1742 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1744 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1755 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1761 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1763 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1767 if (SE.isSCEVable(
PHI->getType()))
1768 SE.forgetValue(
PHI);
1769 if (
PHI->hasNUsesOrMore(1))
1772 PHI->eraseFromParent();
1780 for (PHINode *LCPHI : OriginalFC0PHIs) {
1781 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1782 assert(L1LatchBBIdx >= 0 &&
1783 "Expected loop carried value to be rewired at this point!");
1785 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1787 PHINode *L1HeaderPHI =
1794 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1805 simplifyLatchBranch(FC0);
1809 if (FC0.Latch != FC0.ExitingBlock)
1811 DominatorTree::Insert, FC0.Latch, FC1.Header));
1813 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1814 FC0.Latch, FC0.Header));
1815 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1816 FC1.Latch, FC0.Header));
1817 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1818 FC1.Latch, FC1.Header));
1827 DTU.applyUpdates(TreeUpdates);
1829 LI.removeBlock(FC1GuardBlock);
1830 LI.removeBlock(FC1.Preheader);
1831 LI.removeBlock(FC0.ExitBlock);
1833 LI.removeBlock(FC0ExitBlockSuccessor);
1834 DTU.deleteBB(FC0ExitBlockSuccessor);
1836 DTU.deleteBB(FC1GuardBlock);
1837 DTU.deleteBB(FC1.Preheader);
1838 DTU.deleteBB(FC0.ExitBlock);
1845 SE.forgetLoop(FC1.L);
1846 SE.forgetLoop(FC0.L);
1849 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1850 for (BasicBlock *BB : Blocks) {
1853 if (LI.getLoopFor(BB) != FC1.L)
1855 LI.changeLoopFor(BB, FC0.L);
1858 const auto &ChildLoopIt = FC1.L->
begin();
1859 Loop *ChildLoop = *ChildLoopIt;
1870 SE.forgetBlockAndLoopDispositions();
1874 mergeLatch(FC0, FC1);
1878 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1906 for (
auto &L : LI) {
1913 LoopFuser LF(LI, DT, DI, SE, PDT, ORE,
DL, AC,
TTI);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
std::list< FusionCandidate > FusionCandidateList
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
static void printLoopVector(const LoopVector &LV)
SmallVector< Loop *, 4 > LoopVector
static cl::opt< bool > VerboseFusionDebugging("loop-fusion-verbose-debug", cl::desc("Enable verbose debugging for Loop Fusion"), cl::Hidden, cl::init(false))
static cl::opt< unsigned > FusionPeelMaxCount("loop-fusion-peel-max-count", cl::init(0), cl::Hidden, cl::desc("Max number of iterations to be peeled from a loop, such that " "fusion can take place"))
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
LLVM Basic Block Representation.
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const Instruction & front() const
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 * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
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.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
A parsed version of the target data layout string in and methods for querying it.
AnalysisPass to compute dependence information in a function.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Analysis pass that exposes the LoopInfo for a function.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
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.
unsigned getLoopDepth() const
Return the nesting level of this loop.
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.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
reverse_iterator rend() const
reverse_iterator rbegin() const
Represents a single loop in the control flow graph.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
@ BasicBlock
Various leaf nodes.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
bool succ_empty(const Instruction *I)
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.
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
LLVM_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
bool canPeel(const Loop *L)
auto reverse(ContainerTy &&C)
TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint, DominatorTree &DT, const PostDominatorTree *PDT=nullptr, DependenceInfo *DI=nullptr, bool CheckForEntireBlock=false)
Return true if I can be safely moved before InsertPoint.