74#define DEBUG_TYPE "loop-fusion"
77STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
78STATISTIC(InvalidPreheader,
"Loop has invalid preheader");
80STATISTIC(InvalidExitingBlock,
"Loop has invalid exiting blocks");
81STATISTIC(InvalidExitBlock,
"Loop has invalid exit block");
84STATISTIC(AddressTakenBB,
"Basic block has address taken");
85STATISTIC(MayThrowException,
"Loop may throw an exception");
86STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
87STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
88STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
89STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
90STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
91STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
95 "Loop has a non-empty preheader with instructions that cannot be moved");
96STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
97STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
98STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
99 "instructions that cannot be moved");
100STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
101 "instructions that cannot be moved");
104 "The second candidate is guarded while the first one is not");
105STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
106STATISTIC(NumSunkInsts,
"Number of hoisted preheader instructions.");
115 "loop-fusion-dependence-analysis",
116 cl::desc(
"Which dependence analysis should loop fusion use?"),
118 "Use the scalar evolution interface"),
120 "Use the dependence analysis interface"),
122 "Use all available analyses")),
127 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
128 "fusion can take place"));
133 cl::desc(
"Enable verbose debugging for Loop Fusion"),
148struct FusionCandidate {
191 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
192 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
193 Latch(L->getLoopLatch()), L(L), Valid(
true),
194 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
195 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
202 if (BB->hasAddressTaken()) {
214 if (
StoreInst *SI = dyn_cast<StoreInst>(&
I)) {
215 if (
SI->isVolatile()) {
221 if (
LoadInst *LI = dyn_cast<LoadInst>(&
I)) {
222 if (LI->isVolatile()) {
228 if (
I.mayWriteToMemory())
230 if (
I.mayReadFromMemory())
238 return Preheader && Header && ExitingBlock && ExitBlock && Latch &&
L &&
239 !
L->isInvalid() && Valid;
245 assert(!
L->isInvalid() &&
"Loop is invalid!");
246 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
247 assert(Header ==
L->getHeader() &&
"Header is out of sync");
248 assert(ExitingBlock ==
L->getExitingBlock() &&
249 "Exiting Blocks is out of sync");
250 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
251 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
268 void updateAfterPeeling() {
269 Preheader =
L->getLoopPreheader();
270 Header =
L->getHeader();
271 ExitingBlock =
L->getExitingBlock();
272 ExitBlock =
L->getExitBlock();
273 Latch =
L->getLoopLatch();
285 assert(GuardBranch &&
"Only valid on guarded loops.");
287 "Expecting guard to be a conditional branch.");
295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
297 dbgs() <<
"\tGuardBranch: ";
299 dbgs() << *GuardBranch;
303 << (GuardBranch ? GuardBranch->
getName() :
"nullptr") <<
"\n"
304 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
306 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
308 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
309 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
311 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
313 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
329 ++InvalidExitingBlock;
343 <<
" trip count not computable!\n");
347 if (!
L->isLoopSimplifyForm()) {
349 <<
" is not in simplified form!\n");
353 if (!
L->isRotatedForm()) {
376 assert(L && Preheader &&
"Fusion candidate not initialized properly!");
380 L->getStartLoc(), Preheader)
382 <<
"Loop is not a candidate for fusion: " << Stat.getDesc());
388struct FusionCandidateCompare {
399 bool operator()(
const FusionCandidate &LHS,
400 const FusionCandidate &RHS)
const {
408 assert(DT &&
LHS.PDT &&
"Expecting valid dominator tree");
411 if (DT->
dominates(RHSEntryBlock, LHSEntryBlock)) {
414 assert(
LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
418 if (DT->
dominates(LHSEntryBlock, RHSEntryBlock)) {
420 assert(
LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
432 if (WrongOrder && RightOrder) {
439 }
else if (WrongOrder)
448 "No dominance relationship between these fusion candidates!");
464using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
469 const FusionCandidate &FC) {
471 OS <<
FC.Preheader->getName();
479 const FusionCandidateSet &CandSet) {
480 for (
const FusionCandidate &FC : CandSet)
487printFusionCandidates(
const FusionCandidateCollection &FusionCandidates) {
488 dbgs() <<
"Fusion Candidates: \n";
489 for (
const auto &CandidateSet : FusionCandidates) {
490 dbgs() <<
"*** Fusion Candidate Set ***\n";
491 dbgs() << CandidateSet;
492 dbgs() <<
"****************************\n";
503struct LoopDepthTree {
510 LoopsOnLevel.emplace_back(LoopVector(LI.
rbegin(), LI.
rend()));
515 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
519 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
523 LoopsOnLevelTy LoopsOnNextLevel;
525 for (
const LoopVector &LV : *
this)
527 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
528 LoopsOnNextLevel.emplace_back(LoopVector(
L->begin(),
L->end()));
530 LoopsOnLevel = LoopsOnNextLevel;
531 RemovedLoops.clear();
535 bool empty()
const {
return size() == 0; }
536 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
537 unsigned getDepth()
const {
return Depth; }
539 iterator
begin() {
return LoopsOnLevel.begin(); }
540 iterator
end() {
return LoopsOnLevel.end(); }
553 LoopsOnLevelTy LoopsOnLevel;
557static void printLoopVector(
const LoopVector &LV) {
558 dbgs() <<
"****************************\n";
561 dbgs() <<
"****************************\n";
568 FusionCandidateCollection FusionCandidates;
587 : LDT(LI), DTU(DT, PDT,
DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
588 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC),
TTI(
TTI) {}
600 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
602 bool Changed =
false;
604 while (!LDT.empty()) {
605 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
606 << LDT.getDepth() <<
"\n";);
608 for (
const LoopVector &LV : LDT) {
609 assert(LV.size() > 0 &&
"Empty loop set was build!");
618 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
624 collectFusionCandidates(LV);
625 Changed |= fuseCandidates();
636 FusionCandidates.clear();
661 const FusionCandidate &FC1)
const {
662 assert(FC0.Preheader && FC1.Preheader &&
"Expecting valid preheaders");
664 return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
671 void collectFusionCandidates(
const LoopVector &LV) {
675 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
676 if (!CurrCand.isEligibleForFusion(SE))
684 bool FoundSet =
false;
686 for (
auto &CurrCandSet : FusionCandidates) {
688 CurrCandSet.insert(CurrCand);
693 <<
" to existing candidate set\n");
704 FusionCandidateSet NewCandSet;
705 NewCandSet.insert(CurrCand);
706 FusionCandidates.push_back(NewCandSet);
708 NumFusionCandidates++;
717 bool isBeneficialFusion(
const FusionCandidate &FC0,
718 const FusionCandidate &FC1) {
730 std::pair<bool, std::optional<unsigned>>
731 haveIdenticalTripCounts(
const FusionCandidate &FC0,
732 const FusionCandidate &FC1)
const {
734 if (isa<SCEVCouldNotCompute>(TripCount0)) {
735 UncomputableTripCount++;
736 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
737 return {
false, std::nullopt};
741 if (isa<SCEVCouldNotCompute>(TripCount1)) {
742 UncomputableTripCount++;
743 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
744 return {
false, std::nullopt};
748 << *TripCount1 <<
" are "
749 << (TripCount0 == TripCount1 ?
"identical" :
"different")
752 if (TripCount0 == TripCount1)
756 "determining the difference between trip counts\n");
765 if (TC0 == 0 || TC1 == 0) {
766 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
767 "have a constant number of iterations. Peeling "
768 "is not benefical\n");
769 return {
false, std::nullopt};
772 std::optional<unsigned> Difference;
773 int Diff = TC0 - TC1;
779 dbgs() <<
"Difference is less than 0. FC1 (second loop) has more "
780 "iterations than the first one. Currently not supported\n");
783 LLVM_DEBUG(
dbgs() <<
"Difference in loop trip count is: " << Difference
786 return {
false, Difference};
789 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
790 unsigned PeelCount) {
791 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
794 <<
" iterations of the first loop. \n");
797 FC0.Peeled =
peelLoop(FC0.L, PeelCount, &LI, &SE, DT, &AC,
true, VMap);
802 auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
804 assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
805 "Loops should have identical trip counts after peeling");
808 FC0.PP.PeelCount += PeelCount;
813 FC0.updateAfterPeeling();
829 if (Pred != FC0.ExitBlock) {
838 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
840 Succ = CurrentBranch->getSuccessor(1);
848 dbgs() <<
"Sucessfully peeled " << FC0.PP.PeelCount
849 <<
" iterations from the first loop.\n"
850 "Both Loops have the same number of iterations now.\n");
861 bool fuseCandidates() {
863 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
864 for (
auto &CandidateSet : FusionCandidates) {
865 if (CandidateSet.size() < 2)
869 << CandidateSet <<
"\n");
871 for (
auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
872 assert(!LDT.isRemovedLoop(FC0->L) &&
873 "Should not have removed loops in CandidateSet!");
875 for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
876 assert(!LDT.isRemovedLoop(FC1->L) &&
877 "Should not have removed loops in CandidateSet!");
879 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0->dump();
880 dbgs() <<
" with\n"; FC1->dump();
dbgs() <<
"\n");
890 std::pair<bool, std::optional<unsigned>> IdenticalTripCountRes =
891 haveIdenticalTripCounts(*FC0, *FC1);
892 bool SameTripCount = IdenticalTripCountRes.first;
893 std::optional<unsigned> TCDifference = IdenticalTripCountRes.second;
897 if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
900 <<
"Difference in loop trip counts: " << *TCDifference
901 <<
" is greater than maximum peel count specificed: "
906 SameTripCount =
true;
910 if (!SameTripCount) {
911 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
912 "counts. Not fusing.\n");
913 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
918 if (!isAdjacent(*FC0, *FC1)) {
920 <<
"Fusion candidates are not adjacent. Not fusing.\n");
921 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
925 if ((!FC0->GuardBranch && FC1->GuardBranch) ||
926 (FC0->GuardBranch && !FC1->GuardBranch)) {
928 "another one is not. Not fusing.\n");
929 reportLoopFusion<OptimizationRemarkMissed>(
930 *FC0, *FC1, OnlySecondCandidateIsGuarded);
936 if (FC0->GuardBranch && FC1->GuardBranch &&
937 !haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
939 "guards. Not Fusing.\n");
940 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
945 if (FC0->GuardBranch) {
946 assert(FC1->GuardBranch &&
"Expecting valid FC1 guard branch");
949 *FC1->ExitBlock->getFirstNonPHIOrDbg(), DT,
952 "instructions in exit block. Not fusing.\n");
953 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
959 *FC1->GuardBranch->getParent(),
960 *FC0->GuardBranch->getParent()->getTerminator(), DT, &PDT,
963 <<
"Fusion candidate contains unsafe "
964 "instructions in guard block. Not fusing.\n");
965 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
973 if (!dependencesAllowFusion(*FC0, *FC1)) {
974 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
975 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
976 InvalidDependencies);
988 if (!isEmptyPreheader(*FC1)) {
994 if (!collectMovablePreheaderInsts(*FC0, *FC1, SafeToHoist,
997 "Fusion Candidate Pre-header.\n"
999 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
1005 bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
1007 <<
"\tFusion appears to be "
1008 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
1009 if (!BeneficialToFuse) {
1010 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
1011 FusionNotBeneficial);
1019 movePreheaderInsts(*FC0, *FC1, SafeToHoist, SafeToSink);
1021 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << *FC0 <<
" and "
1024 FusionCandidate FC0Copy = *FC0;
1027 bool Peel = TCDifference && *TCDifference > 0;
1029 peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
1035 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
1038 FusionCandidate FusedCand(
1039 performFusion((Peel ? FC0Copy : *FC0), *FC1), DT, &PDT, ORE,
1042 assert(FusedCand.isEligibleForFusion(SE) &&
1043 "Fused candidate should be eligible for fusion!");
1046 LDT.removeLoop(FC1->L);
1048 CandidateSet.erase(FC0);
1049 CandidateSet.erase(FC1);
1051 auto InsertPos = CandidateSet.insert(FusedCand);
1053 assert(InsertPos.second &&
1054 "Unable to insert TargetCandidate in CandidateSet!");
1059 FC0 = FC1 = InsertPos.first;
1061 LLVM_DEBUG(
dbgs() <<
"Candidate Set (after fusion): " << CandidateSet
1079 const FusionCandidate &FC0)
const {
1081 assert(FC0PreheaderTarget &&
1082 "Expected single successor for loop preheader.");
1084 for (
Use &Op :
I.operands()) {
1085 if (
auto *OpInst = dyn_cast<Instruction>(Op)) {
1089 if (!(OpHoisted || DT.
dominates(OpInst, FC0PreheaderTarget))) {
1097 if (isa<PHINode>(
I))
1101 if (!
I.mayReadOrWriteMemory())
1104 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
1106 if (
auto D = DI.
depends(&
I, NotHoistedInst,
true)) {
1109 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
1111 "preheader that is not being hoisted.\n");
1118 if (
auto D = DI.
depends(ReadInst, &
I,
true)) {
1121 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
1128 if (
auto D = DI.
depends(WriteInst, &
I,
true)) {
1130 if (
D->isFlow() ||
D->isOutput()) {
1131 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1142 bool canSinkInst(
Instruction &
I,
const FusionCandidate &FC1)
const {
1143 for (
User *U :
I.users()) {
1144 if (
auto *UI{dyn_cast<Instruction>(U)}) {
1147 if (FC1.L->contains(UI)) {
1156 if (!
I.mayReadOrWriteMemory())
1160 if (
auto D = DI.
depends(&
I, ReadInst,
true)) {
1163 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1170 if (
auto D = DI.
depends(&
I, WriteInst,
true)) {
1172 if (
D->isOutput() ||
D->isAnti()) {
1173 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1184 bool collectMovablePreheaderInsts(
1185 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1195 if (&
I == FC1Preheader->getTerminator())
1201 if (
I.mayThrow() || !
I.willReturn()) {
1202 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1208 if (
I.isAtomic() ||
I.isVolatile()) {
1210 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1214 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1221 if (canSinkInst(
I, FC1)) {
1231 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1246 if (ExprL == &OldL) {
1251 if (OldL.contains(ExprL)) {
1253 if (!UseMax || !Pos || !Expr->
isAffine()) {
1265 bool wasValidSCEV()
const {
return Valid; }
1269 const Loop &OldL, &NewL;
1285 LLVM_DEBUG(
dbgs() <<
" Access function check: " << *SCEVPtr0 <<
" vs "
1286 << *SCEVPtr1 <<
"\n");
1288 AddRecLoopReplacer
Rewriter(SE, L0, L1);
1289 SCEVPtr0 =
Rewriter.visit(SCEVPtr0);
1292 LLVM_DEBUG(
dbgs() <<
" Access function after rewrite: " << *SCEVPtr0
1293 <<
" [Valid: " <<
Rewriter.wasValidSCEV() <<
"]\n");
1303 auto HasNonLinearDominanceRelation = [&](
const SCEV *S) {
1314 EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
1319 << (IsAlwaysGE ?
" >= " :
" may < ") << *SCEVPtr1
1328 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1334 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
" : "
1335 << DepChoice <<
"\n");
1338 switch (DepChoice) {
1340 return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
1342 auto DepResult = DI.
depends(&I0, &I1,
true);
1348 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1349 << (DepResult->isOrdered() ?
"true" :
"false")
1351 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1356 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1358 dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1365 return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
1367 dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
1375 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1376 const FusionCandidate &FC1) {
1377 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1379 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
1384 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1387 InvalidDependencies++;
1391 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
1394 InvalidDependencies++;
1401 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1404 InvalidDependencies++;
1408 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
1411 InvalidDependencies++;
1420 for (
auto &Op :
I.operands())
1422 if (FC0.L->contains(
Def->getParent())) {
1423 InvalidDependencies++;
1439 bool isAdjacent(
const FusionCandidate &FC0,
1440 const FusionCandidate &FC1)
const {
1442 if (FC0.GuardBranch)
1443 return FC0.getNonLoopBlock() == FC1.getEntryBlock();
1445 return FC0.ExitBlock == FC1.getEntryBlock();
1448 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1449 return FC.Preheader->size() == 1;
1454 void movePreheaderInsts(
const FusionCandidate &FC0,
1455 const FusionCandidate &FC1,
1459 assert(HoistInsts.
size() + SinkInsts.
size() == FC1.Preheader->size() - 1 &&
1460 "Attempting to sink and hoist preheader instructions, but not all "
1461 "the preheader instructions are accounted for.");
1463 NumHoistedInsts += HoistInsts.
size();
1464 NumSunkInsts += SinkInsts.
size();
1467 if (!HoistInsts.
empty())
1468 dbgs() <<
"Hoisting: \n";
1470 dbgs() << *
I <<
"\n";
1471 if (!SinkInsts.
empty())
1472 dbgs() <<
"Sinking: \n";
1474 dbgs() << *
I <<
"\n";
1478 assert(
I->getParent() == FC1.Preheader);
1479 I->moveBefore(FC0.Preheader->getTerminator());
1483 assert(
I->getParent() == FC1.Preheader);
1484 I->moveBefore(&*FC1.ExitBlock->getFirstInsertionPt());
1500 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1501 const FusionCandidate &FC1)
const {
1502 assert(FC0.GuardBranch && FC1.GuardBranch &&
1503 "Expecting FC0 and FC1 to be guarded loops.");
1505 if (
auto FC0CmpInst =
1506 dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
1507 if (
auto FC1CmpInst =
1508 dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
1509 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1515 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1516 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1518 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1523 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1524 BranchInst *FCLatchBranch = dyn_cast<BranchInst>(
FC.Latch->getTerminator());
1525 if (FCLatchBranch) {
1528 "Expecting the two successors of FCLatchBranch to be the same");
1537 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1574 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1575 assert(FC0.isValid() && FC1.isValid() &&
1576 "Expecting valid fusion candidates");
1579 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1588 if (FC0.GuardBranch)
1589 return fuseGuardedLoops(FC0, FC1);
1592 (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
1593 assert(FC1.Preheader->size() == 1 &&
1594 FC1.Preheader->getSingleSuccessor() == FC1.Header);
1606 if (FC0.ExitingBlock != FC0.Latch)
1611 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1612 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1635 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1638 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1640 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1643 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1646 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1649 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1650 FC0.ExitBlock->getTerminator()->eraseFromParent();
1652 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1658 FC1.Preheader->getTerminator()->eraseFromParent();
1661 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1664 while (
PHINode *
PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1667 if (
PHI->hasNUsesOrMore(1))
1668 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1670 PHI->eraseFromParent();
1678 for (
PHINode *LCPHI : OriginalFC0PHIs) {
1679 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1680 assert(L1LatchBBIdx >= 0 &&
1681 "Expected loop carried value to be rewired at this point!");
1683 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1686 LCV->
getType(), 2, LCPHI->getName() +
".afterFC0", L1HeaderIP);
1691 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1695 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1696 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1700 simplifyLatchBranch(FC0);
1704 if (FC0.Latch != FC0.ExitingBlock)
1706 DominatorTree::Insert, FC0.Latch, FC1.Header));
1709 FC0.Latch, FC0.Header));
1711 FC1.Latch, FC0.Header));
1713 FC1.Latch, FC1.Header));
1737 mergeLatch(FC0, FC1);
1742 FC0.L->addBlockEntry(BB);
1743 FC1.L->removeBlockFromLoop(BB);
1748 while (!FC1.L->isInnermost()) {
1749 const auto &ChildLoopIt = FC1.L->begin();
1750 Loop *ChildLoop = *ChildLoopIt;
1760 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
1783 template <
typename RemarkKind>
1784 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1786 assert(FC0.Preheader && FC1.Preheader &&
1787 "Expecting valid fusion candidates");
1788 using namespace ore;
1789#if LLVM_ENABLE_STATS
1791 ORE.
emit(RemarkKind(
DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
1793 <<
"[" << FC0.Preheader->getParent()->getName()
1794 <<
"]: " <<
NV(
"Cand1",
StringRef(FC0.Preheader->getName()))
1795 <<
" and " <<
NV(
"Cand2",
StringRef(FC1.Preheader->getName()))
1796 <<
": " << Stat.getDesc());
1815 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1816 const FusionCandidate &FC1) {
1817 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1821 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1822 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1830 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1837 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1850 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1852 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1856 FC1.GuardBranch->eraseFromParent();
1860 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1862 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1864 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1866 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1871 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1874 FC0ExitBlockSuccessor);
1878 "Expecting guard block to have no predecessors");
1880 "Expecting guard block to have no successors");
1895 if (FC0.ExitingBlock != FC0.Latch)
1899 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1902 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1903 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1918 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1922 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1924 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1934 FC0.ExitBlock->getTerminator()->eraseFromParent();
1940 FC1.Preheader->getTerminator()->eraseFromParent();
1943 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1946 while (
PHINode *
PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1949 if (
PHI->hasNUsesOrMore(1))
1950 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1952 PHI->eraseFromParent();
1960 for (
PHINode *LCPHI : OriginalFC0PHIs) {
1961 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1962 assert(L1LatchBBIdx >= 0 &&
1963 "Expected loop carried value to be rewired at this point!");
1965 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1968 LCV->
getType(), 2, LCPHI->getName() +
".afterFC0", L1HeaderIP);
1973 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1979 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1980 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1984 simplifyLatchBranch(FC0);
1988 if (FC0.Latch != FC0.ExitingBlock)
1990 DominatorTree::Insert, FC0.Latch, FC1.Header));
1993 FC0.Latch, FC0.Header));
1995 FC1.Latch, FC0.Header));
1997 FC1.Latch, FC1.Header));
2013 DTU.
deleteBB(FC0ExitBlockSuccessor);
2030 mergeLatch(FC0, FC1);
2035 FC0.L->addBlockEntry(BB);
2036 FC1.L->removeBlockFromLoop(BB);
2041 while (!FC1.L->isInnermost()) {
2042 const auto &ChildLoopIt = FC1.L->begin();
2043 Loop *ChildLoop = *ChildLoopIt;
2053 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
2080 bool Changed =
false;
2081 for (
auto &L : LI) {
2088 LoopFuser LF(LI, DT, DI, SE, PDT, ORE,
DL, AC,
TTI);
2089 Changed |= LF.fuseLoops(
F);
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 clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static cl::opt< FusionDependenceAnalysisChoice > FusionDependenceAnalysis("loop-fusion-dependence-analysis", cl::desc("Which dependence analysis should loop fusion use?"), cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev", "Use the scalar evolution interface"), clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da", "Use the dependence analysis interface"), clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all", "Use all available analyses")), cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL))
FusionDependenceAnalysisChoice
@ FUSION_DEPENDENCE_ANALYSIS_DA
@ FUSION_DEPENDENCE_ANALYSIS_ALL
@ FUSION_DEPENDENCE_ANALYSIS_SCEV
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.
mir Rename Register Operands
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Virtual Register Rewriter
A container for analyses that lazily runs them and caches their results.
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.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
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.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Conditional or Unconditional Branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
A parsed version of the target data layout string in and methods for querying it.
AnalysisPass to compute dependence information in a function.
DependenceInfo - This class is the main dependence-analysis driver.
std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool PossiblyLoopIndependent)
depends - Tests for a dependence between the Src and Dst instructions.
unsigned getLevel() const
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock * getParent() const
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
BlockT * getHeader() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void print(raw_ostream &OS) const
reverse_iterator rend() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
reverse_iterator rbegin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Represents a single loop in the control flow graph.
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="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
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.
void preserve()
Mark an analysis as preserved.
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStart() const
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
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
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
ArrayRef< const SCEV * > operands() const
This visitor recursively visits a SCEV expression and re-writes it.
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
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...
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...
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
StringRef getName() const
Return a constant reference to the value's name.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
const_iterator end(StringRef path)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
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)
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)
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
void append_range(Container &C, Range &&R)
Wrapper function to append a range to a container.
bool canPeel(const Loop *L)
void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
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)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isControlFlowEquivalent(const Instruction &I0, const Instruction &I1, const DominatorTree &DT, const PostDominatorTree &PDT)
Return true if I0 and I1 are control flow equivalent.
bool nonStrictlyPostDominate(const BasicBlock *ThisBlock, const BasicBlock *OtherBlock, const DominatorTree *DT, const PostDominatorTree *PDT)
In case that two BBs ThisBlock and OtherBlock are control flow equivalent but they do not strictly do...
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
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.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
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)
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.
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
bool peelLoop(Loop *L, unsigned PeelCount, 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...
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.