70#define DEBUG_TYPE "loop-fusion"
73STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
74STATISTIC(InvalidLoopStructure,
"Loop has invalid structure");
75STATISTIC(AddressTakenBB,
"Basic block has address taken");
76STATISTIC(MayThrowException,
"Loop may throw an exception");
77STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
78STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
79STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
80STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
81STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
82STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
85 "Loop has a non-empty preheader with instructions that cannot be moved");
86STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
87STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
88STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
89 "instructions that cannot be moved");
90STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
91 "instructions that cannot be moved");
94 "The second candidate is guarded while the first one is not");
95STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
96STATISTIC(NumSunkInsts,
"Number of hoisted preheader instructions.");
101 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
102 "fusion can take place"));
107 cl::desc(
"Enable verbose debugging for Loop Fusion"),
122struct FusionCandidate {
161 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
162 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
163 Latch(L->getLoopLatch()), L(L), Valid(
true),
164 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
165 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
172 if (BB->hasAddressTaken()) {
174 reportInvalidCandidate(AddressTakenBB);
185 if (
SI->isVolatile()) {
192 if (LI->isVolatile()) {
198 if (
I.mayWriteToMemory())
199 MemWrites.push_back(&
I);
200 if (
I.mayReadFromMemory())
201 MemReads.push_back(&
I);
208 return Preheader && ExitingBlock && ExitBlock && Latch &&
L &&
215 assert(!
L->isInvalid() &&
"Loop is invalid!");
216 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
217 assert(Header ==
L->getHeader() &&
"Header is out of sync");
218 assert(ExitingBlock ==
L->getExitingBlock() &&
219 "Exiting Blocks is out of sync");
220 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
221 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
231 return GuardBranch->getParent();
237 void updateAfterPeeling() {
238 Preheader =
L->getLoopPreheader();
239 Header =
L->getHeader();
240 ExitingBlock =
L->getExitingBlock();
241 ExitBlock =
L->getExitBlock();
242 Latch =
L->getLoopLatch();
254 assert(GuardBranch &&
"Only valid on guarded loops.");
262#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
264 dbgs() <<
"\tGuardBranch: ";
266 dbgs() << *GuardBranch;
270 << (GuardBranch ? GuardBranch->getName() :
"nullptr") <<
"\n"
271 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
273 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
275 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
276 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
278 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
280 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
291 assert(Header &&
"Header should be guaranteed to exist!");
292 ++InvalidLoopStructure;
299 <<
" trip count not computable!\n");
303 if (!
L->isLoopSimplifyForm()) {
305 <<
" is not in simplified form!\n");
309 if (!
L->isRotatedForm()) {
333 L->getStartLoc(),
L->getHeader())
334 <<
"Loop is not a candidate for fusion");
339 L->getStartLoc(),
L->getHeader())
340 <<
"[" <<
L->getHeader()->getParent()->getName() <<
"]: "
341 <<
"Loop is not a candidate for fusion: " << Stat.getDesc());
358 dbgs() <<
"****************************\n";
359 for (
const Loop *L : LV)
361 dbgs() <<
"****************************\n";
366 OS << FC.Preheader->getName();
375 for (
const FusionCandidate &FC : CandList)
383 dbgs() <<
"Fusion Candidates: \n";
384 for (
const auto &CandidateList : FusionCandidates) {
385 dbgs() <<
"*** Fusion Candidate List ***\n";
386 dbgs() << CandidateList;
387 dbgs() <<
"****************************\n";
400struct LoopDepthTree {
401 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
405 LoopDepthTree(LoopInfo &LI) : Depth(1) {
412 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
416 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
420 LoopsOnLevelTy LoopsOnNextLevel;
424 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
425 LoopsOnNextLevel.emplace_back(
LoopVector(
L->begin(),
L->end()));
427 LoopsOnLevel = LoopsOnNextLevel;
428 RemovedLoops.clear();
432 bool empty()
const {
return size() == 0; }
433 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
434 unsigned getDepth()
const {
return Depth; }
436 iterator
begin() {
return LoopsOnLevel.begin(); }
437 iterator
end() {
return LoopsOnLevel.end(); }
438 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
439 const_iterator
end()
const {
return LoopsOnLevel.end(); }
444 SmallPtrSet<const Loop *, 8> RemovedLoops;
450 LoopsOnLevelTy LoopsOnLevel;
465 PostDominatorTree &PDT;
466 OptimizationRemarkEmitter &ORE;
468 const TargetTransformInfo &TTI;
471 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
472 ScalarEvolution &SE, PostDominatorTree &PDT,
473 OptimizationRemarkEmitter &ORE,
const DataLayout &
DL,
474 AssumptionCache &AC,
const TargetTransformInfo &TTI)
475 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
476 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
481 bool fuseLoops(Function &
F) {
488 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
492 while (!LDT.empty()) {
493 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
494 << LDT.getDepth() <<
"\n";);
497 assert(LV.size() > 0 &&
"Empty loop set was build!");
506 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
512 collectFusionCandidates(LV);
517 FusionCandidates.clear();
543 void collectFusionCandidates(
const LoopVector &LV) {
547 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
548 if (!CurrCand.isEligibleForFusion(SE))
556 bool FoundAdjacent =
false;
557 for (
auto &CurrCandList : FusionCandidates) {
558 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
559 CurrCandList.push_back(CurrCand);
560 FoundAdjacent =
true;
561 NumFusionCandidates++;
565 <<
" to existing candidate list\n");
570 if (!FoundAdjacent) {
577 NewCandList.push_back(CurrCand);
578 FusionCandidates.push_back(NewCandList);
588 bool isBeneficialFusion(
const FusionCandidate &FC0,
589 const FusionCandidate &FC1) {
601 std::pair<bool, std::optional<unsigned>>
602 haveIdenticalTripCounts(
const FusionCandidate &FC0,
603 const FusionCandidate &FC1)
const {
604 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
606 UncomputableTripCount++;
607 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
608 return {
false, std::nullopt};
611 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
613 UncomputableTripCount++;
614 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
615 return {
false, std::nullopt};
619 << *TripCount1 <<
" are "
620 << (TripCount0 == TripCount1 ?
"identical" :
"different")
623 if (TripCount0 == TripCount1)
627 "determining the difference between trip counts\n");
631 const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
632 const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
636 if (TC0 == 0 || TC1 == 0) {
637 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
638 "have a constant number of iterations. Peeling "
639 "is not benefical\n");
640 return {
false, std::nullopt};
643 std::optional<unsigned> Difference;
644 int Diff = TC0 - TC1;
650 dbgs() <<
"Difference is less than 0. FC1 (second loop) has more "
651 "iterations than the first one. Currently not supported\n");
654 LLVM_DEBUG(
dbgs() <<
"Difference in loop trip count is: " << Difference
657 return {
false, Difference};
660 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
661 unsigned PeelCount) {
662 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
665 <<
" iterations of the first loop. \n");
668 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
true, VMap);
673 auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
675 assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
676 "Loops should have identical trip counts after peeling");
682 PDT.recalculate(*FC0.Preheader->
getParent());
684 FC0.updateAfterPeeling();
698 SmallVector<Instruction *, 8> WorkList;
700 if (Pred != FC0.ExitBlock) {
703 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
708 for (Instruction *CurrentBranch : WorkList) {
709 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
711 Succ = CurrentBranch->getSuccessor(1);
715 DTU.applyUpdates(TreeUpdates);
720 <<
" iterations from the first loop.\n"
721 "Both Loops have the same number of iterations now.\n");
731 bool fuseCandidates() {
734 for (
auto &CandidateList : FusionCandidates) {
735 if (CandidateList.size() < 2)
739 << CandidateList <<
"\n");
741 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
742 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
747 assert(!LDT.isRemovedLoop(FC0.L) &&
748 "Should not have removed loops in CandidateList!");
749 assert(!LDT.isRemovedLoop(FC1.L) &&
750 "Should not have removed loops in CandidateList!");
752 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
753 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
763 std::pair<bool, std::optional<unsigned>> IdenticalTripCountRes =
764 haveIdenticalTripCounts(FC0, FC1);
765 bool SameTripCount = IdenticalTripCountRes.first;
766 std::optional<unsigned> TCDifference = IdenticalTripCountRes.second;
770 if (FC0.AbleToPeel && !SameTripCount && TCDifference) {
773 <<
"Difference in loop trip counts: " << *TCDifference
774 <<
" is greater than maximum peel count specificed: "
779 SameTripCount =
true;
783 if (!SameTripCount) {
784 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
785 "counts. Not fusing.\n");
786 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
791 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
792 (FC0.GuardBranch && !FC1.GuardBranch)) {
794 "another one is not. Not fusing.\n");
795 reportLoopFusion<OptimizationRemarkMissed>(
796 FC0, FC1, OnlySecondCandidateIsGuarded);
802 if (FC0.GuardBranch && FC1.GuardBranch &&
803 !haveIdenticalGuards(FC0, FC1) && !TCDifference) {
805 "guards. Not Fusing.\n");
806 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
811 if (FC0.GuardBranch) {
812 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
818 "instructions in exit block. Not fusing.\n");
819 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
825 *FC1.GuardBranch->getParent(),
826 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
829 "instructions in guard block. Not fusing.\n");
830 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
838 if (!dependencesAllowFusion(FC0, FC1)) {
839 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
840 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
841 InvalidDependencies);
848 SmallVector<Instruction *, 4> SafeToHoist;
849 SmallVector<Instruction *, 4> SafeToSink;
853 if (!isEmptyPreheader(FC1)) {
859 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
862 "Fusion Candidate Pre-header.\n"
864 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
870 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
872 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
873 if (!BeneficialToFuse) {
874 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
875 FusionNotBeneficial);
883 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
885 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
888 FusionCandidate FC0Copy = FC0;
891 bool Peel = TCDifference && *TCDifference > 0;
893 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
899 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
902 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
903 DT, &PDT, ORE, FC0Copy.PP);
905 assert(FusedCand.isEligibleForFusion(SE) &&
906 "Fused candidate should be eligible for fusion!");
909 LDT.removeLoop(FC1.L);
912 It = CandidateList.erase(It);
913 It = CandidateList.erase(It);
914 It = CandidateList.insert(It, FusedCand);
919 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
933 bool canHoistInst(Instruction &
I,
934 const SmallVector<Instruction *, 4> &SafeToHoist,
935 const SmallVector<Instruction *, 4> &NotHoisting,
936 const FusionCandidate &FC0)
const {
938 assert(FC0PreheaderTarget &&
939 "Expected single successor for loop preheader.");
941 for (Use &
Op :
I.operands()) {
946 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
958 if (!
I.mayReadOrWriteMemory())
961 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
962 for (Instruction *NotHoistedInst : NotHoisting) {
963 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
966 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
968 "preheader that is not being hoisted.\n");
974 for (Instruction *ReadInst : FC0.MemReads) {
975 if (
auto D = DI.depends(ReadInst, &
I)) {
978 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
984 for (Instruction *WriteInst : FC0.MemWrites) {
985 if (
auto D = DI.depends(WriteInst, &
I)) {
987 if (
D->isFlow() ||
D->isOutput()) {
988 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
999 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1000 for (User *U :
I.users()) {
1013 if (!
I.mayReadOrWriteMemory())
1016 for (Instruction *ReadInst : FC1.MemReads) {
1017 if (
auto D = DI.depends(&
I, ReadInst)) {
1020 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1026 for (Instruction *WriteInst : FC1.MemWrites) {
1027 if (
auto D = DI.depends(&
I, WriteInst)) {
1029 if (
D->isOutput() ||
D->isAnti()) {
1030 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1041 bool collectMovablePreheaderInsts(
1042 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1043 SmallVector<Instruction *, 4> &SafeToHoist,
1044 SmallVector<Instruction *, 4> &SafeToSink)
const {
1048 SmallVector<Instruction *, 4> NotHoisting;
1050 for (Instruction &
I : *FC1Preheader) {
1052 if (&
I == FC1Preheader->getTerminator())
1058 if (
I.mayThrow() || !
I.willReturn()) {
1059 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1065 if (
I.isAtomic() ||
I.isVolatile()) {
1067 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1071 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1078 if (canSinkInst(
I, FC1)) {
1088 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1094 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1095 const FusionCandidate &FC1, Instruction &I0,
1099 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1102 auto DepResult = DI.depends(&I0, &I1);
1108 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1109 << (DepResult->isOrdered() ?
"true" :
"false")
1111 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1115 unsigned Levels = DepResult->getLevels();
1116 unsigned SameSDLevels = DepResult->getSameSDLevels();
1120 if (CurLoopLevel > Levels + SameSDLevels)
1124 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1126 unsigned Direction = DepResult->getDirection(Level,
false);
1132 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1139 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1141 if (DepResult->isScalar(CurLoopLevel,
true) && !DepResult->isAnti()) {
1142 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to a loop-invariant non-anti "
1148 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1158 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1164 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1165 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1171 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1172 const FusionCandidate &FC1) {
1173 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1176 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1178 for (Instruction *WriteL0 : FC0.MemWrites) {
1179 for (Instruction *WriteL1 : FC1.MemWrites)
1180 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1183 for (Instruction *ReadL1 : FC1.MemReads)
1184 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1189 for (Instruction *WriteL1 : FC1.MemWrites) {
1190 for (Instruction *WriteL0 : FC0.MemWrites)
1191 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1194 for (Instruction *ReadL0 : FC0.MemReads)
1195 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1202 for (BasicBlock *BB : FC1.L->
blocks())
1203 for (Instruction &
I : *BB)
1204 for (
auto &
Op :
I.operands())
1225 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1226 const FusionCandidate &FC1)
const {
1228 if (FC0.GuardBranch)
1229 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1231 return FC0.ExitBlock == FC1.getEntryBlock();
1234 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1235 return FC.Preheader->size() == 1;
1240 void movePreheaderInsts(
const FusionCandidate &FC0,
1241 const FusionCandidate &FC1,
1242 SmallVector<Instruction *, 4> &HoistInsts,
1243 SmallVector<Instruction *, 4> &SinkInsts)
const {
1246 "Attempting to sink and hoist preheader instructions, but not all "
1247 "the preheader instructions are accounted for.");
1249 NumHoistedInsts += HoistInsts.
size();
1250 NumSunkInsts += SinkInsts.
size();
1253 if (!HoistInsts.
empty())
1254 dbgs() <<
"Hoisting: \n";
1255 for (Instruction *
I : HoistInsts)
1256 dbgs() << *
I <<
"\n";
1257 if (!SinkInsts.
empty())
1258 dbgs() <<
"Sinking: \n";
1259 for (Instruction *
I : SinkInsts)
1260 dbgs() << *
I <<
"\n";
1263 for (Instruction *
I : HoistInsts) {
1264 assert(
I->getParent() == FC1.Preheader);
1265 I->moveBefore(*FC0.Preheader,
1269 for (Instruction *
I :
reverse(SinkInsts)) {
1270 assert(
I->getParent() == FC1.Preheader);
1278 "Expected the sunk PHI node to have 1 incoming value.");
1279 I->replaceAllUsesWith(
I->getOperand(0));
1280 I->eraseFromParent();
1298 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1299 const FusionCandidate &FC1)
const {
1300 assert(FC0.GuardBranch && FC1.GuardBranch &&
1301 "Expecting FC0 and FC1 to be guarded loops.");
1303 if (
auto FC0CmpInst =
1305 if (
auto FC1CmpInst =
1307 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1314 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1316 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1321 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1323 if (FCLatchBranch) {
1325 "Expecting the two successors of FCLatchBranch to be the same");
1326 UncondBrInst *NewBranch =
1334 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1371 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1372 assert(FC0.isValid() && FC1.isValid() &&
1373 "Expecting valid fusion candidates");
1376 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1385 if (FC0.GuardBranch)
1386 return fuseGuardedLoops(FC0, FC1);
1403 if (FC0.ExitingBlock != FC0.Latch)
1404 for (PHINode &
PHI : FC0.Header->
phis())
1435 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1437 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1440 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1446 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1449 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1450 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1456 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1458 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1462 if (SE.isSCEVable(
PHI->getType()))
1463 SE.forgetValue(
PHI);
1464 if (
PHI->hasNUsesOrMore(1))
1467 PHI->eraseFromParent();
1475 for (PHINode *LCPHI : OriginalFC0PHIs) {
1476 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1477 assert(L1LatchBBIdx >= 0 &&
1478 "Expected loop carried value to be rewired at this point!");
1480 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1482 PHINode *L1HeaderPHI =
1489 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1498 simplifyLatchBranch(FC0);
1502 if (FC0.Latch != FC0.ExitingBlock)
1504 DominatorTree::Insert, FC0.Latch, FC1.Header));
1506 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1507 FC0.Latch, FC0.Header));
1508 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1509 FC1.Latch, FC0.Header));
1510 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1511 FC1.Latch, FC1.Header));
1514 DTU.applyUpdates(TreeUpdates);
1516 LI.removeBlock(FC1.Preheader);
1517 DTU.deleteBB(FC1.Preheader);
1519 LI.removeBlock(FC0.ExitBlock);
1520 DTU.deleteBB(FC0.ExitBlock);
1529 SE.forgetLoop(FC1.L);
1530 SE.forgetLoop(FC0.L);
1533 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1534 for (BasicBlock *BB : Blocks) {
1537 if (LI.getLoopFor(BB) != FC1.L)
1539 LI.changeLoopFor(BB, FC0.L);
1542 const auto &ChildLoopIt = FC1.L->
begin();
1543 Loop *ChildLoop = *ChildLoopIt;
1554 SE.forgetBlockAndLoopDispositions();
1558 mergeLatch(FC0, FC1);
1562 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1585 template <
typename RemarkKind>
1586 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1588 assert(FC0.Preheader && FC1.Preheader &&
1589 "Expecting valid fusion candidates");
1590 using namespace ore;
1591#if LLVM_ENABLE_STATS
1596 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName()))
1597 <<
" and " <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName()))
1598 <<
": " << Stat.getDesc());
1617 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1618 const FusionCandidate &FC1) {
1619 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1621 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1622 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1623 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1624 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1632 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1639 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1652 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1654 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1658 FC1.GuardBranch->eraseFromParent();
1659 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1662 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1664 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1666 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1668 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1672 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1675 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1677 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1678 FC0ExitBlockSuccessor);
1682 "Expecting guard block to have no predecessors");
1684 "Expecting guard block to have no successors");
1699 if (FC0.ExitingBlock != FC0.Latch)
1700 for (PHINode &
PHI : FC0.Header->
phis())
1703 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1726 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1728 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1739 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1745 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1747 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1751 if (SE.isSCEVable(
PHI->getType()))
1752 SE.forgetValue(
PHI);
1753 if (
PHI->hasNUsesOrMore(1))
1756 PHI->eraseFromParent();
1764 for (PHINode *LCPHI : OriginalFC0PHIs) {
1765 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1766 assert(L1LatchBBIdx >= 0 &&
1767 "Expected loop carried value to be rewired at this point!");
1769 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1771 PHINode *L1HeaderPHI =
1778 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1789 simplifyLatchBranch(FC0);
1793 if (FC0.Latch != FC0.ExitingBlock)
1795 DominatorTree::Insert, FC0.Latch, FC1.Header));
1797 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1798 FC0.Latch, FC0.Header));
1799 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1800 FC1.Latch, FC0.Header));
1801 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1802 FC1.Latch, FC1.Header));
1811 DTU.applyUpdates(TreeUpdates);
1813 LI.removeBlock(FC1GuardBlock);
1814 LI.removeBlock(FC1.Preheader);
1815 LI.removeBlock(FC0.ExitBlock);
1817 LI.removeBlock(FC0ExitBlockSuccessor);
1818 DTU.deleteBB(FC0ExitBlockSuccessor);
1820 DTU.deleteBB(FC1GuardBlock);
1821 DTU.deleteBB(FC1.Preheader);
1822 DTU.deleteBB(FC0.ExitBlock);
1829 SE.forgetLoop(FC1.L);
1830 SE.forgetLoop(FC0.L);
1833 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1834 for (BasicBlock *BB : Blocks) {
1837 if (LI.getLoopFor(BB) != FC1.L)
1839 LI.changeLoopFor(BB, FC0.L);
1842 const auto &ChildLoopIt = FC1.L->
begin();
1843 Loop *ChildLoop = *ChildLoopIt;
1854 SE.forgetBlockAndLoopDispositions();
1858 mergeLatch(FC0, FC1);
1862 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1890 for (
auto &L : LI) {
1897 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.