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(ContainsAtomicAccess,
"Loop contains an atomic access");
79STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
80STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
81STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
82STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
83STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
86 "Loop has a non-empty preheader with instructions that cannot be moved");
87STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
88STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
89STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block with "
90 "instructions that cannot be moved");
91STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block with "
92 "instructions that cannot be moved");
95 "The second candidate is guarded while the first one is not");
96STATISTIC(NumHoistedInsts,
"Number of hoisted preheader instructions.");
97STATISTIC(NumSunkInsts,
"Number of sunk preheader instructions.");
102 cl::desc(
"Max number of iterations to be peeled from a loop, such that "
103 "fusion can take place"));
108 cl::desc(
"Enable verbose debugging for Loop Fusion"),
123struct FusionCandidate {
162 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
163 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
164 Latch(L->getLoopLatch()), L(L), Valid(
true),
165 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(
canPeel(L)),
166 Peeled(
false), DT(DT), PDT(PDT), ORE(ORE) {
173 if (BB->hasAddressTaken()) {
175 reportInvalidCandidate(AddressTakenBB);
185 if (
I.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) {
598 std::optional<int64_t>
599 calculateTripCountDiff(
const FusionCandidate &FC0,
600 const FusionCandidate &FC1)
const {
601 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
603 UncomputableTripCount++;
604 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
608 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
610 UncomputableTripCount++;
611 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
616 << *TripCount1 <<
" are "
617 << (TripCount0 == TripCount1 ?
"identical" :
"different")
620 if (TripCount0 == TripCount1)
624 "determining the difference between trip counts\n");
631 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC0.L));
633 static_cast<int64_t
>(SE.getSmallConstantTripCount(FC1.L));
637 if (TC0 == 0 || TC1 == 0) {
638 LLVM_DEBUG(
dbgs() <<
"Loop(s) do not have a single exit point or do not "
639 "have a constant number of iterations. Peeling "
640 "is not benefical\n");
647 void peelFusionCandidate(FusionCandidate &FC0,
const FusionCandidate &FC1,
648 unsigned PeelCount) {
649 assert(FC0.AbleToPeel &&
"Should be able to peel loop");
652 <<
" iterations of the first loop. \n");
658 peelLoop(FC0.L, PeelCount,
false, &LI, &SE, DT, &AC,
664 auto TCDiff = calculateTripCountDiff(FC0, FC1);
666 assert(TCDiff && *TCDiff == 0 &&
667 "Loops should have identical trip counts after peeling");
673 PDT.recalculate(*FC0.Preheader->
getParent());
675 FC0.updateAfterPeeling();
689 SmallVector<Instruction *, 8> WorkList;
691 if (Pred != FC0.ExitBlock) {
694 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
699 for (Instruction *CurrentBranch : WorkList) {
700 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
702 Succ = CurrentBranch->getSuccessor(1);
706 DTU.applyUpdates(TreeUpdates);
711 <<
" iterations from the first loop.\n"
712 "Both Loops have the same number of iterations now.\n");
722 bool fuseCandidates() {
725 for (
auto &CandidateList : FusionCandidates) {
726 if (CandidateList.size() < 2)
730 << CandidateList <<
"\n");
732 for (
auto It = CandidateList.begin(), NextIt = std::next(It);
733 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
738 assert(!LDT.isRemovedLoop(FC0.L) &&
739 "Should not have removed loops in CandidateList!");
740 assert(!LDT.isRemovedLoop(FC1.L) &&
741 "Should not have removed loops in CandidateList!");
743 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0.dump();
744 dbgs() <<
" with\n"; FC1.dump();
dbgs() <<
"\n");
749 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
755 FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
758 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
759 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip "
760 "counts and peeling is not supported for this "
761 "case. Not fusing.\n");
762 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
767 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
768 (FC0.GuardBranch && !FC1.GuardBranch)) {
770 "another one is not. Not fusing.\n");
771 reportLoopFusion<OptimizationRemarkMissed>(
772 FC0, FC1, OnlySecondCandidateIsGuarded);
779 if (!TCDifference || *TCDifference == 0) {
780 if (FC0.GuardBranch && FC1.GuardBranch &&
781 !haveIdenticalGuards(FC0, FC1)) {
783 "guards. Not Fusing.\n");
784 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
790 if (FC0.GuardBranch) {
791 assert(FC1.GuardBranch &&
"Expecting valid FC1 guard branch");
797 "instructions in exit block. Not fusing.\n");
798 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
804 *FC1.GuardBranch->getParent(),
805 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
808 "instructions in guard block. Not fusing.\n");
809 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
817 if (!dependencesAllowFusion(FC0, FC1)) {
818 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
819 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
820 InvalidDependencies);
827 SmallVector<Instruction *, 4> SafeToHoist;
828 SmallVector<Instruction *, 4> SafeToSink;
832 if (!isEmptyPreheader(FC1)) {
838 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
841 "Fusion Candidate Pre-header.\n"
843 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
849 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
851 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
852 if (!BeneficialToFuse) {
853 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
854 FusionNotBeneficial);
862 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
864 LLVM_DEBUG(
dbgs() <<
"\tFusion is performed: " << FC0 <<
" and " << FC1
867 FusionCandidate FC0Copy = FC0;
870 bool Peel = TCDifference && *TCDifference > 0;
872 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
878 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
881 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
882 DT, &PDT, ORE, FC0Copy.PP);
884 assert(FusedCand.isEligibleForFusion(SE) &&
885 "Fused candidate should be eligible for fusion!");
888 LDT.removeLoop(FC1.L);
891 It = CandidateList.erase(It);
892 It = CandidateList.erase(It);
893 It = CandidateList.insert(It, FusedCand);
898 LLVM_DEBUG(
dbgs() <<
"Candidate List (after fusion): " << CandidateList
912 bool canHoistInst(Instruction &
I,
913 const SmallVector<Instruction *, 4> &SafeToHoist,
914 const SmallVector<Instruction *, 4> &NotHoisting,
915 const FusionCandidate &FC0)
const {
917 assert(FC0PreheaderTarget &&
918 "Expected single successor for loop preheader.");
920 for (Use &
Op :
I.operands()) {
925 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
937 if (!
I.mayReadOrWriteMemory())
940 LLVM_DEBUG(
dbgs() <<
"Checking if this mem inst can be hoisted.\n");
941 for (Instruction *NotHoistedInst : NotHoisting) {
942 if (
auto D = DI.depends(&
I, NotHoistedInst)) {
945 if (
D->isFlow() ||
D->isAnti() ||
D->isOutput()) {
947 "preheader that is not being hoisted.\n");
953 for (Instruction *ReadInst : FC0.MemReads) {
954 if (
auto D = DI.depends(ReadInst, &
I)) {
957 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC0.\n");
963 for (Instruction *WriteInst : FC0.MemWrites) {
964 if (
auto D = DI.depends(WriteInst, &
I)) {
966 if (
D->isFlow() ||
D->isOutput()) {
967 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC0.\n");
978 bool canSinkInst(Instruction &
I,
const FusionCandidate &FC1)
const {
979 for (User *U :
I.users()) {
992 if (!
I.mayReadOrWriteMemory())
995 for (Instruction *ReadInst : FC1.MemReads) {
996 if (
auto D = DI.depends(&
I, ReadInst)) {
999 LLVM_DEBUG(
dbgs() <<
"Inst depends on a read instruction in FC1.\n");
1005 for (Instruction *WriteInst : FC1.MemWrites) {
1006 if (
auto D = DI.depends(&
I, WriteInst)) {
1008 if (
D->isOutput() ||
D->isAnti()) {
1009 LLVM_DEBUG(
dbgs() <<
"Inst depends on a write instruction in FC1.\n");
1020 bool collectMovablePreheaderInsts(
1021 const FusionCandidate &FC0,
const FusionCandidate &FC1,
1022 SmallVector<Instruction *, 4> &SafeToHoist,
1023 SmallVector<Instruction *, 4> &SafeToSink)
const {
1027 SmallVector<Instruction *, 4> NotHoisting;
1029 for (Instruction &
I : *FC1Preheader) {
1031 if (&
I == FC1Preheader->getTerminator())
1037 if (
I.mayThrow() || !
I.willReturn()) {
1038 LLVM_DEBUG(
dbgs() <<
"Inst: " <<
I <<
" may throw or won't return.\n");
1044 if (
I.isAtomic() ||
I.isVolatile()) {
1046 dbgs() <<
"\tInstruction is volatile or atomic. Cannot move it.\n");
1050 if (canHoistInst(
I, SafeToHoist, NotHoisting, FC0)) {
1057 if (canSinkInst(
I, FC1)) {
1067 dbgs() <<
"All preheader instructions could be sunk or hoisted!\n");
1073 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1074 const FusionCandidate &FC1, Instruction &I0,
1078 LLVM_DEBUG(
dbgs() <<
"Check dep: " << I0 <<
" vs " << I1 <<
"\n");
1081 auto DepResult = DI.depends(&I0, &I1);
1087 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: "
1088 << (DepResult->isOrdered() ?
"true" :
"false")
1090 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
1094 unsigned Levels = DepResult->getLevels();
1095 unsigned SameSDLevels = DepResult->getSameSDLevels();
1099 if (CurLoopLevel > Levels + SameSDLevels)
1103 for (
unsigned Level = 1;
Level <= std::min(CurLoopLevel - 1, Levels);
1105 unsigned Direction = DepResult->getDirection(Level,
false);
1111 LLVM_DEBUG(
dbgs() <<
"Safe to fuse due to non-equal acceses in the "
1118 assert(CurLoopLevel > Levels &&
"Fusion candidates are not separated");
1120 if (DepResult->isScalar(CurLoopLevel,
true)) {
1121 if (DepResult->isInput() || DepResult->isOutput()) {
1123 << (DepResult->isInput() ?
"input" :
"output")
1124 <<
" dependency\n");
1129 dbgs() <<
"Not safe to fuse due to a scalar flow dependency\n");
1133 unsigned CurDir = DepResult->getDirection(CurLoopLevel,
true);
1143 LLVM_DEBUG(
dbgs() <<
"Safe to fuse with no backward loop-carried "
1149 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1150 LLVM_DEBUG(
dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
1156 bool dependencesAllowFusion(
const FusionCandidate &FC0,
1157 const FusionCandidate &FC1) {
1158 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
1161 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1163 for (Instruction *WriteL0 : FC0.MemWrites) {
1164 for (Instruction *WriteL1 : FC1.MemWrites)
1165 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1168 for (Instruction *ReadL1 : FC1.MemReads)
1169 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1174 for (Instruction *WriteL1 : FC1.MemWrites) {
1175 for (Instruction *WriteL0 : FC0.MemWrites)
1176 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1179 for (Instruction *ReadL0 : FC0.MemReads)
1180 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1187 for (BasicBlock *BB : FC1.L->
blocks())
1188 for (Instruction &
I : *BB)
1189 for (
auto &
Op :
I.operands())
1210 bool isStrictlyAdjacent(
const FusionCandidate &FC0,
1211 const FusionCandidate &FC1)
const {
1213 if (FC0.GuardBranch)
1214 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1216 return FC0.ExitBlock == FC1.getEntryBlock();
1219 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1220 return FC.Preheader->size() == 1;
1225 void movePreheaderInsts(
const FusionCandidate &FC0,
1226 const FusionCandidate &FC1,
1227 SmallVector<Instruction *, 4> &HoistInsts,
1228 SmallVector<Instruction *, 4> &SinkInsts)
const {
1231 "Attempting to sink and hoist preheader instructions, but not all "
1232 "the preheader instructions are accounted for.");
1234 NumHoistedInsts += HoistInsts.
size();
1235 NumSunkInsts += SinkInsts.
size();
1238 if (!HoistInsts.
empty())
1239 dbgs() <<
"Hoisting: \n";
1240 for (Instruction *
I : HoistInsts)
1241 dbgs() << *
I <<
"\n";
1242 if (!SinkInsts.
empty())
1243 dbgs() <<
"Sinking: \n";
1244 for (Instruction *
I : SinkInsts)
1245 dbgs() << *
I <<
"\n";
1248 for (Instruction *
I : HoistInsts) {
1249 assert(
I->getParent() == FC1.Preheader);
1250 I->moveBefore(*FC0.Preheader,
1254 for (Instruction *
I :
reverse(SinkInsts)) {
1255 assert(
I->getParent() == FC1.Preheader);
1263 "Expected the sunk PHI node to have 1 incoming value.");
1264 I->replaceAllUsesWith(
I->getOperand(0));
1265 I->eraseFromParent();
1283 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1284 const FusionCandidate &FC1)
const {
1285 assert(FC0.GuardBranch && FC1.GuardBranch &&
1286 "Expecting FC0 and FC1 to be guarded loops.");
1290 if ((!FC0CmpInst || !FC1CmpInst) &&
1294 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1301 return (FC1.GuardBranch->
getSuccessor(0) == FC1.Preheader);
1302 return (FC1.GuardBranch->
getSuccessor(1) == FC1.Preheader);
1307 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1309 if (FCLatchBranch) {
1311 "Expecting the two successors of FCLatchBranch to be the same");
1312 UncondBrInst *NewBranch =
1320 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1357 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1358 assert(FC0.isValid() && FC1.isValid() &&
1359 "Expecting valid fusion candidates");
1362 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1371 if (FC0.GuardBranch)
1372 return fuseGuardedLoops(FC0, FC1);
1389 if (FC0.ExitingBlock != FC0.Latch)
1390 for (PHINode &
PHI : FC0.Header->
phis())
1421 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1423 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1426 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1432 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1435 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1436 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1442 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1444 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1448 if (SE.isSCEVable(
PHI->getType()))
1449 SE.forgetValue(
PHI);
1450 if (
PHI->hasNUsesOrMore(1))
1453 PHI->eraseFromParent();
1461 for (PHINode *LCPHI : OriginalFC0PHIs) {
1462 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1463 assert(L1LatchBBIdx >= 0 &&
1464 "Expected loop carried value to be rewired at this point!");
1466 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1468 PHINode *L1HeaderPHI =
1475 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1484 simplifyLatchBranch(FC0);
1488 if (FC0.Latch != FC0.ExitingBlock)
1490 DominatorTree::Insert, FC0.Latch, FC1.Header));
1492 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1493 FC0.Latch, FC0.Header));
1494 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1495 FC1.Latch, FC0.Header));
1496 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1497 FC1.Latch, FC1.Header));
1500 DTU.applyUpdates(TreeUpdates);
1502 LI.removeBlock(FC1.Preheader);
1503 DTU.deleteBB(FC1.Preheader);
1505 LI.removeBlock(FC0.ExitBlock);
1506 DTU.deleteBB(FC0.ExitBlock);
1515 SE.forgetLoop(FC1.L);
1516 SE.forgetLoop(FC0.L);
1519 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1520 for (BasicBlock *BB : Blocks) {
1523 if (LI.getLoopFor(BB) != FC1.L)
1525 LI.changeLoopFor(BB, FC0.L);
1528 const auto &ChildLoopIt = FC1.L->
begin();
1529 Loop *ChildLoop = *ChildLoopIt;
1540 SE.forgetBlockAndLoopDispositions();
1544 mergeLatch(FC0, FC1);
1548 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1571 template <
typename RemarkKind>
1572 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1574 assert(FC0.Preheader && FC1.Preheader &&
1575 "Expecting valid fusion candidates");
1576 using namespace ore;
1577#if LLVM_ENABLE_STATS
1582 <<
"]: " <<
NV(
"Cand1", StringRef(FC0.Preheader->
getName()))
1583 <<
" and " <<
NV(
"Cand2", StringRef(FC1.Preheader->
getName()))
1584 <<
": " << Stat.getDesc());
1603 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1604 const FusionCandidate &FC1) {
1605 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1607 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1608 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1609 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1610 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1618 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1625 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1638 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1640 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1644 FC1.GuardBranch->eraseFromParent();
1645 new UnreachableInst(FC1GuardBlock->
getContext(), FC1GuardBlock);
1648 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1650 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1652 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1654 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1658 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1661 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1663 new UnreachableInst(FC0ExitBlockSuccessor->
getContext(),
1664 FC0ExitBlockSuccessor);
1668 "Expecting guard block to have no predecessors");
1670 "Expecting guard block to have no successors");
1685 if (FC0.ExitingBlock != FC0.Latch)
1686 for (PHINode &
PHI : FC0.Header->
phis())
1689 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1712 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1714 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1725 new UnreachableInst(FC0.ExitBlock->
getContext(), FC0.ExitBlock);
1731 new UnreachableInst(FC1.Preheader->
getContext(), FC1.Preheader);
1733 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1737 if (SE.isSCEVable(
PHI->getType()))
1738 SE.forgetValue(
PHI);
1739 if (
PHI->hasNUsesOrMore(1))
1742 PHI->eraseFromParent();
1750 for (PHINode *LCPHI : OriginalFC0PHIs) {
1751 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1752 assert(L1LatchBBIdx >= 0 &&
1753 "Expected loop carried value to be rewired at this point!");
1755 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1757 PHINode *L1HeaderPHI =
1764 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1775 simplifyLatchBranch(FC0);
1779 if (FC0.Latch != FC0.ExitingBlock)
1781 DominatorTree::Insert, FC0.Latch, FC1.Header));
1783 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1784 FC0.Latch, FC0.Header));
1785 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1786 FC1.Latch, FC0.Header));
1787 TreeUpdates.
emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1788 FC1.Latch, FC1.Header));
1797 DTU.applyUpdates(TreeUpdates);
1799 LI.removeBlock(FC1GuardBlock);
1800 LI.removeBlock(FC1.Preheader);
1801 LI.removeBlock(FC0.ExitBlock);
1803 LI.removeBlock(FC0ExitBlockSuccessor);
1804 DTU.deleteBB(FC0ExitBlockSuccessor);
1806 DTU.deleteBB(FC1GuardBlock);
1807 DTU.deleteBB(FC1.Preheader);
1808 DTU.deleteBB(FC0.ExitBlock);
1815 SE.forgetLoop(FC1.L);
1816 SE.forgetLoop(FC0.L);
1819 SmallVector<BasicBlock *, 8> Blocks(FC1.L->
blocks());
1820 for (BasicBlock *BB : Blocks) {
1823 if (LI.getLoopFor(BB) != FC1.L)
1825 LI.changeLoopFor(BB, FC0.L);
1828 const auto &ChildLoopIt = FC1.L->
begin();
1829 Loop *ChildLoop = *ChildLoopIt;
1840 SE.forgetBlockAndLoopDispositions();
1844 mergeLatch(FC0, FC1);
1848 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1876 for (
auto &L : LI) {
1883 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 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
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
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.
LLVM_ABI 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...
LLVM_ABI bool canPeel(const Loop *L)
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.