72#define DEBUG_TYPE "loop-fusion"
75STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
76STATISTIC(InvalidLoopStructure,
"Loop has invalid structure");
77STATISTIC(AddressTakenBB,
"Basic block has address taken");
78STATISTIC(MayThrowException,
"Loop may throw an exception");
79STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
80STATISTIC(ContainsAtomicAccess,
"Loop contains an atomic access");
81STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
82STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
83STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
84STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
85STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
88 "Loop has a non-empty preheader with instructions that cannot be moved");
89STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
90STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
91STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
92 "instructions that cannot be moved");
93STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
94 "instructions that cannot be moved");
97 "The second candidate is guarded while the first one is not");
98STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
99STATISTIC(NumSunkInsts,
"Number of sunk preheader instructions.");
104 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
105 "fusion can take place"));
110 cl::desc(
"Enable verbose debugging for Loop Fusion"),
125struct FusionCandidate {
164 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
165 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
166 Latch(L->getLoopLatch()), L(L), Valid(
true),
167 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
168 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
175 if (BB->hasAddressTaken()) {
178 reportInvalidCandidate(
"AddressTakenBB",
179 "Basic block has address taken");
188 "Loop may throw an exception");
191 if (
I.isVolatile()) {
193 ++ContainsVolatileAccess;
195 "Loop contains a volatile access");
203 ++ContainsAtomicAccess;
205 "Loop contains an atomic access");
208 if (
I.mayWriteToMemory())
209 MemWrites.push_back(&
I);
210 if (
I.mayReadFromMemory())
211 MemReads.push_back(&
I);
218 return Preheader && ExitingBlock && ExitBlock && Latch &&
L &&
225 assert(!
L->isInvalid() &&
"Loop is invalid!");
226 assert(Preheader ==
L->getLoopPreheader() &&
"Preheader is out of sync");
227 assert(Header ==
L->getHeader() &&
"Header is out of sync");
228 assert(ExitingBlock ==
L->getExitingBlock() &&
229 "Exiting Blocks is out of sync");
230 assert(ExitBlock ==
L->getExitBlock() &&
"Exit block is out of sync");
231 assert(Latch ==
L->getLoopLatch() &&
"Latch is out of sync");
247 void updateAfterPeeling() {
248 Preheader =
L->getLoopPreheader();
249 Header =
L->getHeader();
250 ExitingBlock =
L->getExitingBlock();
251 ExitBlock =
L->getExitBlock();
252 Latch =
L->getLoopLatch();
264 assert(GuardBranch &&
"Only valid on guarded loops.");
272#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
274 dbgs() <<
"\tGuardBranch: ";
276 dbgs() << *GuardBranch;
280 << (GuardBranch ? GuardBranch->
getName() :
"nullptr") <<
"\n"
281 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
283 <<
"\tHeader: " << (Header ? Header->getName() :
"nullptr") <<
"\n"
285 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n"
286 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
288 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n"
290 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
301 assert(Header &&
"Header should be guaranteed to exist!");
302 ++InvalidLoopStructure;
309 <<
" trip count not computable!\n");
312 "Loop has unknown trip count");
315 if (!
L->isLoopSimplifyForm()) {
317 <<
" is not in simplified form!\n");
320 "Loop is not in simplified form");
323 if (!
L->isRotatedForm()) {
352 L->getStartLoc(),
L->getHeader())
353 <<
"Loop is not a candidate for fusion");
356 L->getStartLoc(),
L->getHeader())
357 <<
"[" <<
L->getHeader()->getParent()->getName() <<
"]: "
358 <<
"Loop is not a candidate for fusion: " << RemarkMsg);
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";
430 if (!L->isLoopSimplifyForm() || !L->isRotatedForm())
433 BasicBlock *Preheader = L->getLoopPreheader();
434 BasicBlock *ExitBlock = L->getUniqueExitBlock();
446 BasicBlock *SkipBB = GuardBI->getSuccessor(0) == Preheader
447 ? GuardBI->getSuccessor(1)
448 : GuardBI->getSuccessor(0);
449 if (SkipBB == Preheader)
460 if (!MergeBB || MergeBB == SkipBB || MergeBB == GuardBB ||
471 <<
" of loop " << L->getHeader()->getName() <<
"\n");
474 GuardBI->replaceSuccessorWith(SkipBB, MergeBB);
496struct LoopDepthTree {
497 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
501 LoopDepthTree(LoopInfo &LI) : Depth(1) {
508 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
512 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
516 LoopsOnLevelTy LoopsOnNextLevel;
520 if (!isRemovedLoop(L) &&
L->begin() !=
L->end())
521 LoopsOnNextLevel.emplace_back(
LoopVector(
L->begin(),
L->end()));
523 LoopsOnLevel = LoopsOnNextLevel;
524 RemovedLoops.clear();
528 bool empty()
const {
return size() == 0; }
529 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
530 unsigned getDepth()
const {
return Depth; }
532 iterator
begin() {
return LoopsOnLevel.begin(); }
533 iterator
end() {
return LoopsOnLevel.end(); }
534 const_iterator
begin()
const {
return LoopsOnLevel.begin(); }
535 const_iterator
end()
const {
return LoopsOnLevel.end(); }
540 SmallPtrSet<const Loop *, 8> RemovedLoops;
546 LoopsOnLevelTy LoopsOnLevel;
561 PostDominatorTree &PDT;
562 OptimizationRemarkEmitter &ORE;
564 const TargetTransformInfo &TTI;
567 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
568 ScalarEvolution &SE, PostDominatorTree &PDT,
569 OptimizationRemarkEmitter &ORE, AssumptionCache &AC,
570 const TargetTransformInfo &TTI)
571 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
572 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
584 LLVM_DEBUG(
dbgs() <<
"Performing Loop Fusion on function " <<
F.getName()
588 while (!LDT.empty()) {
589 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth "
590 << LDT.getDepth() <<
"\n";);
593 assert(LV.size() > 0 &&
"Empty loop set was build!");
602 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
608 collectFusionCandidates(LV);
613 FusionCandidates.clear();
639 void collectFusionCandidates(
const LoopVector &LV) {
643 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
644 if (!CurrCand.isEligibleForFusion(SE))
652 bool FoundAdjacent =
false;
653 for (
auto &CurrCandList : FusionCandidates) {
654 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
655 CurrCandList.push_back(CurrCand);
656 FoundAdjacent =
true;
657 NumFusionCandidates++;
661 <<
" to existing candidate list\n");
666 if (!FoundAdjacent) {
673 NewCandList.push_back(CurrCand);
674 FusionCandidates.push_back(NewCandList);
684 bool isBeneficialFusion(
const FusionCandidate &FC0,
685 const FusionCandidate &FC1) {
694 std::optional<int64_t>
695 calculateTripCountDiff(
const FusionCandidate &FC0,
696 const FusionCandidate &FC1)
const {
697 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
699 UncomputableTripCount++;
700 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
704 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
706 UncomputableTripCount++;
707 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
712 << *TripCount1 <<
" are "
713 << (TripCount0 == TripCount1 ?
"identical" :
"different")
716 if (TripCount0 == TripCount1)
720 "determining the difference between trip counts\n");
727 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC0.L));
729 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC1.L));
733 if (TC0 == 0 || TC1 == 0) {
734 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
735 "have a constant number of iterations. Peeling "
736 "is not benefical\n");
743 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
744 unsigned PeelCount) {
745 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
748 <<
" iterations of the first loop. \n");
754 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
760 auto TCDiff = calculateTripCountDiff(FC0, FC1);
762 assert(TCDiff && *TCDiff == 0 &&
763 "Loops should have identical trip counts after peeling");
769 PDT.recalculate(*FC0.Preheader->
getParent());
771 FC0.updateAfterPeeling();
785 SmallVector<Instruction *, 8> WorkList;
787 if (Pred != FC0.ExitBlock) {
790 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
795 for (Instruction *CurrentBranch : WorkList) {
796 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
798 Succ = CurrentBranch->getSuccessor(1);
802 DTU.applyUpdates(TreeUpdates);
807 <<
" iterations from the first loop.\n"
808 "Both Loops have the same number of iterations now.\n");
818 bool fuseCandidates() {
821 for (
auto &CandidateList : FusionCandidates) {
822 if (CandidateList.size() < 2)
826 << CandidateList <<
"\n");
828 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
829 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
831 const FusionCandidate &FC0 = *It;
832 const FusionCandidate &FC1 = *NextIt;
834 assert(!LDT.isRemovedLoop(FC0.L) &&
835 "Should not have removed loops in CandidateList!");
836 assert(!LDT.isRemovedLoop(FC1.L) &&
837 "Should not have removed loops in CandidateList!");
839 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
840 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
845 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
851 FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
854 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
855 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
856 "counts and peeling is not supported for this "
857 "case. Not fusing.\n");
859 reportLoopFusion<OptimizationRemarkMissed>(
860 FC0, FC1,
"NonEqualTripCount",
861 "Loop trip counts are not the same");
865 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
866 (FC0.GuardBranch && !FC1.GuardBranch)) {
868 "another one is not. Not fusing.\n");
869 ++OnlySecondCandidateIsGuarded;
870 reportLoopFusion<OptimizationRemarkMissed>(
871 FC0, FC1,
"OnlySecondCandidateIsGuarded",
872 "The second candidate is guarded while the first one is not");
882 if (FC0.GuardBranch && FC1.GuardBranch &&
883 !haveIdenticalGuards(FC0, FC1)) {
885 "guards. Not Fusing.\n");
886 ++NonIdenticalGuards;
887 reportLoopFusion<OptimizationRemarkMissed>(
888 FC0, FC1,
"NonIdenticalGuards",
889 "Candidates have different guards");
893 if (FC0.GuardBranch) {
894 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
900 "instructions in exit block. Not fusing.\n");
902 reportLoopFusion<OptimizationRemarkMissed>(
903 FC0, FC1,
"NonEmptyExitBlock",
904 "Candidate has a non-empty exit block with "
905 "instructions that cannot be moved");
911 *FC0.GuardBranch->
getParent()->getTerminator(), DT, &PDT,
914 "instructions in guard block. Not fusing.\n");
915 ++NonEmptyGuardBlock;
916 reportLoopFusion<OptimizationRemarkMissed>(
917 FC0, FC1,
"NonEmptyGuardBlock",
918 "Candidate has a non-empty guard block with "
919 "instructions that cannot be moved");
926 if (!dependencesAllowFusion(FC0, FC1)) {
927 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
928 ++InvalidDependencies;
929 reportLoopFusion<OptimizationRemarkMissed>(
930 FC0, FC1,
"InvalidDependencies",
"Dependencies prevent fusion");
937 SmallVector<Instruction *, 4> SafeToHoist;
938 SmallVector<Instruction *, 4> SafeToSink;
942 if (!isEmptyPreheader(FC1)) {
948 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
951 "Fusion Candidate Pre-header.\n"
954 reportLoopFusion<OptimizationRemarkMissed>(
955 FC0, FC1,
"NonEmptyPreheader",
956 "Loop has a non-empty preheader with instructions that "
962 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
964 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
965 if (!BeneficialToFuse) {
966 ++FusionNotBeneficial;
967 reportLoopFusion<OptimizationRemarkMissed>(
968 FC0, FC1,
"FusionNotBeneficial",
"Fusion is not beneficial");
976 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
978 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
981 FusionCandidate FC0Copy = FC0;
984 bool Peel = TCDifference && *TCDifference > 0;
986 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
993 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
994 "FuseCounter",
"Loops fused");
996 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
997 DT, &PDT, ORE, FC0Copy.PP);
999 assert(FusedCand.isEligibleForFusion(SE) &&
1000 "Fused candidate should be eligible for fusion!");
1003 LDT.removeLoop(FC1.L);
1006 It = CandidateList.erase(It);
1007 It = CandidateList.erase(It);
1008 It = CandidateList.insert(It, FusedCand);
1013 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
1027 bool canHoistInst(Instruction &
I,
1028 const SmallVector<Instruction *, 4> &SafeToHoist,
1029 const SmallVector<Instruction *, 4> &NotHoisting,
1030 const FusionCandidate &FC0)
const {
1032 assert(FC0PreheaderTarget &&
1033 "Expected single successor for loop preheader.");
1035 for (Use &
Op :
I.operands()) {
1040 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
1052 if (!
I.mayReadOrWriteMemory())
1055 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
1056 for (Instruction *NotHoistedInst : NotHoisting) {
1057 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
1060 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
1062 "preheader that is not being hoisted.\n");
1068 for (Instruction *ReadInst : FC0.MemReads) {
1069 if (
auto D = DI.depends(ReadInst, &
I)) {
1072 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
1078 for (Instruction *WriteInst : FC0.MemWrites) {
1079 if (
auto D = DI.depends(WriteInst, &
I)) {
1081 if (
D->isFlow() ||
D->isOutput()) {
1082 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
1093 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
1094 for (User *U :
I.users()) {
1107 if (!
I.mayReadOrWriteMemory())
1110 for (Instruction *ReadInst : FC1.MemReads) {
1111 if (
auto D = DI.depends(&
I, ReadInst)) {
1114 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1120 for (Instruction *WriteInst : FC1.MemWrites) {
1121 if (
auto D = DI.depends(&
I, WriteInst)) {
1123 if (
D->isOutput() ||
D->isAnti()) {
1124 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1135 bool collectMovablePreheaderInsts(
1136 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1137 SmallVector<Instruction *, 4> &SafeToHoist,
1138 SmallVector<Instruction *, 4> &SafeToSink)
const {
1142 SmallVector<Instruction *, 4> NotHoisting;
1144 for (Instruction &
I : *FC1Preheader) {
1146 if (&
I == FC1Preheader->getTerminator())
1152 if (
I.mayThrow() || !
I.willReturn()) {
1153 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1159 if (
I.isAtomic() ||
I.isVolatile()) {
1161 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1165 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1172 if (canSinkInst(
I, FC1)) {
1182 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1188 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1189 const FusionCandidate &FC1, Instruction &I0,
1193 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1196 auto DepResult = DI.depends(&I0, &I1);
1204 if (S0->getValueOperand() ==
S1->getValueOperand())
1210 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1211 << (DepResult->isOrdered() ?
"true" :
"false")
1213 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1217 unsigned Levels = DepResult->getLevels();
1218 unsigned SameSDLevels = DepResult->getSameSDLevels();
1222 if (CurLoopLevel > Levels + SameSDLevels)
1226 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1228 unsigned Direction = DepResult->getDirection(Level,
false);
1234 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1241 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1243 if (DepResult->isScalar(CurLoopLevel,
true)) {
1244 if (DepResult->isInput() || DepResult->isOutput()) {
1246 << (DepResult->isInput() ?
"input" :
"output")
1247 <<
" dependency\n");
1258 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1261 LLVM_DEBUG(
dbgs() <<
"Safe to fuse same-iteration scalar dependence\n");
1266 dbgs() <<
"Not safe to fuse due to a scalar flow dependency\n");
1270 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1280 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1286 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1287 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1293 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1294 const FusionCandidate &FC1) {
1295 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1298 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1302 for (BasicBlock *BB : FC1.L->
blocks())
1303 for (Instruction &
I : *BB)
1304 for (
auto &
Op :
I.operands())
1310 for (Instruction *WriteL0 : FC0.MemWrites) {
1311 for (Instruction *WriteL1 : FC1.MemWrites)
1312 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1315 for (Instruction *ReadL1 : FC1.MemReads)
1316 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1323 for (Instruction *ReadL0 : FC0.MemReads)
1324 for (Instruction *WriteL1 : FC1.MemWrites)
1325 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1344 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1345 const FusionCandidate &FC1)
const {
1347 if (FC0.GuardBranch)
1348 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1350 return FC0.ExitBlock == FC1.getEntryBlock();
1353 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1354 return FC.Preheader->size() == 1;
1359 void movePreheaderInsts(
const FusionCandidate &FC0,
1360 const FusionCandidate &FC1,
1361 SmallVector<Instruction *, 4> &HoistInsts,
1362 SmallVector<Instruction *, 4> &SinkInsts)
const {
1365 "Attempting to sink and hoist preheader instructions, but not all "
1366 "the preheader instructions are accounted for.");
1368 NumHoistedInsts += HoistInsts.
size();
1369 NumSunkInsts += SinkInsts.
size();
1372 if (!HoistInsts.
empty())
1373 dbgs() <<
"Hoisting: \n";
1374 for (Instruction *
I : HoistInsts)
1375 dbgs() << *
I <<
"\n";
1376 if (!SinkInsts.
empty())
1377 dbgs() <<
"Sinking: \n";
1378 for (Instruction *
I : SinkInsts)
1379 dbgs() << *
I <<
"\n";
1382 for (Instruction *
I : HoistInsts) {
1383 assert(
I->getParent() == FC1.Preheader);
1384 I->moveBefore(*FC0.Preheader,
1388 for (Instruction *
I :
reverse(SinkInsts)) {
1389 assert(
I->getParent() == FC1.Preheader);
1397 "Expected the sunk PHI node to have 1 incoming value.");
1398 I->replaceAllUsesWith(
I->getOperand(0));
1399 I->eraseFromParent();
1417 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1418 const FusionCandidate &FC1)
const {
1419 assert(FC0.GuardBranch && FC1.GuardBranch &&
1420 "Expecting FC0 and FC1 to be guarded loops.");
1424 if ((!FC0CmpInst || !FC1CmpInst) &&
1428 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1435 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1436 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1441 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1443 if (FCLatchBranch) {
1445 "Expecting the two successors of FCLatchBranch to be the same");
1446 UncondBrInst *NewBranch =
1454 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1466 void rewireFusedHeaderPHIsAndLatches(
1467 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1468 const SmallVectorImpl<PHINode *> &OriginalFC0PHIs,
1469 SmallVectorImpl<DominatorTree::UpdateType> &TreeUpdates) {
1472 if (SE.isSCEVable(
PHI->getType()))
1473 SE.forgetValue(
PHI);
1474 if (
PHI->hasNUsesOrMore(1))
1477 PHI->eraseFromParent();
1485 for (PHINode *LCPHI : OriginalFC0PHIs) {
1486 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1487 assert(L1LatchBBIdx >= 0 &&
1488 "Expected loop carried value to be rewired at this point!");
1490 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1492 PHINode *L1HeaderPHI =
1499 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1508 simplifyLatchBranch(FC0);
1512 if (FC0.Latch != FC0.ExitingBlock)
1514 DominatorTree::Insert, FC0.Latch, FC1.Header));
1516 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1517 FC0.Latch, FC0.Header));
1518 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1519 FC1.Latch, FC0.Header));
1520 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1521 FC1.Latch, FC1.Header));
1527 Loop *finalizeFusedLoop(
const FusionCandidate &FC0,
1528 const FusionCandidate &FC1) {
1533 SE.forgetLoop(FC1.L);
1534 SE.forgetLoop(FC0.L);
1537 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1538 for (BasicBlock *BB : Blocks) {
1541 if (LI.getLoopFor(BB) != FC1.L)
1543 LI.changeLoopFor(BB, FC0.L);
1546 const auto &ChildLoopIt = FC1.L->
begin();
1547 Loop *ChildLoop = *ChildLoopIt;
1558 SE.forgetBlockAndLoopDispositions();
1562 mergeLatch(FC0, FC1);
1566 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1606 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1607 assert(FC0.isValid() && FC1.isValid() &&
1608 "Expecting valid fusion candidates");
1611 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1620 if (FC0.GuardBranch)
1621 return fuseGuardedLoops(FC0, FC1);
1638 if (FC0.ExitingBlock != FC0.Latch)
1639 for (PHINode &
PHI : FC0.Header->
phis())
1670 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1672 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1675 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1681 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1684 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1685 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1691 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1693 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1695 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1698 DTU.applyUpdates(TreeUpdates);
1700 LI.removeBlock(FC1.Preheader);
1701 DTU.deleteBB(FC1.Preheader);
1703 LI.removeBlock(FC0.ExitBlock);
1704 DTU.deleteBB(FC0.ExitBlock);
1709 return finalizeFusedLoop(FC0, FC1);
1724 template <
typename RemarkKind>
1725 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1726 StringRef RemarkName, StringRef RemarkMsg) {
1727 assert(FC0.Preheader && FC1.Preheader &&
1728 "Expecting valid fusion candidates");
1729 using namespace ore;
1733 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName())) <<
" and "
1734 <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName())) <<
": "
1753 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1754 const FusionCandidate &FC1) {
1755 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1759 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1760 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1768 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1775 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1790 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1795 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1798 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1800 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1802 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1804 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1808 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1811 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1813 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1814 FC0ExitBlockSuccessor);
1818 "Expecting guard block to have no predecessors");
1820 "Expecting guard block to have no successors");
1835 if (FC0.ExitingBlock != FC0.Latch)
1836 for (PHINode &
PHI : FC0.Header->
phis())
1839 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1862 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1864 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1875 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1881 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1883 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1885 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1894 DTU.applyUpdates(TreeUpdates);
1896 LI.removeBlock(FC1GuardBlock);
1897 LI.removeBlock(FC1.Preheader);
1898 LI.removeBlock(FC0.ExitBlock);
1900 LI.removeBlock(FC0ExitBlockSuccessor);
1901 DTU.deleteBB(FC0ExitBlockSuccessor);
1903 DTU.deleteBB(FC1GuardBlock);
1904 DTU.deleteBB(FC1.Preheader);
1905 DTU.deleteBB(FC0.ExitBlock);
1908 return finalizeFusedLoop(FC0, FC1);
1928 for (
auto &L : LI) {
1932 for (
Loop *L : LI.getLoopsInPreorder()) {
1939 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, AC,
TTI);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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 cl::opt< uint32_t > 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"))
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
std::list< FusionCandidate > FusionCandidateList
static bool simplifyLoopGuard(Loop *L, DomTreeUpdater &DTU, LoopInfo &LI, ScalarEvolution &SE)
Fold away an empty block on the "skip" edge of L's loop guard, if any.
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))
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
This file defines the interface for the loop nest analysis.
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.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
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 * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
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
AnalysisPass to compute dependence information in a function.
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
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 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.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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...
bool isLoopHeader(const BlockT *BB) const
reverse_iterator rbegin() const
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
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.
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
This function has undefined behavior.
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.
const ParentTy * getParent() const
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)
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...
LLVM_ABI bool canPeel(const Loop *L)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto reverse(ContainerTy &&C)
LLVM_ABI 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.
LLVM_ABI 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.