70 #define DEBUG_TYPE "loop-fusion" 73 STATISTIC(NumFusionCandidates,
"Number of candidates for loop fusion");
74 STATISTIC(InvalidPreheader,
"Loop has invalid preheader");
75 STATISTIC(InvalidHeader,
"Loop has invalid header");
76 STATISTIC(InvalidExitingBlock,
"Loop has invalid exiting blocks");
77 STATISTIC(InvalidExitBlock,
"Loop has invalid exit block");
78 STATISTIC(InvalidLatch,
"Loop has invalid latch");
79 STATISTIC(InvalidLoop,
"Loop is invalid");
80 STATISTIC(AddressTakenBB,
"Basic block has address taken");
81 STATISTIC(MayThrowException,
"Loop may throw an exception");
82 STATISTIC(ContainsVolatileAccess,
"Loop contains a volatile access");
83 STATISTIC(NotSimplifiedForm,
"Loop is not in simplified form");
84 STATISTIC(InvalidDependencies,
"Dependencies prevent fusion");
85 STATISTIC(UnknownTripCount,
"Loop has unknown trip count");
86 STATISTIC(UncomputableTripCount,
"SCEV cannot compute trip count of loop");
87 STATISTIC(NonEqualTripCount,
"Loop trip counts are not the same");
88 STATISTIC(NonAdjacent,
"Loops are not adjacent");
89 STATISTIC(NonEmptyPreheader,
"Loop has a non-empty preheader");
90 STATISTIC(FusionNotBeneficial,
"Fusion is not beneficial");
91 STATISTIC(NonIdenticalGuards,
"Candidates have different guards");
92 STATISTIC(NonEmptyExitBlock,
"Candidate has a non-empty exit block");
93 STATISTIC(NonEmptyGuardBlock,
"Candidate has a non-empty guard block");
94 STATISTIC(NotRotated,
"Candidate is not rotated");
103 "loop-fusion-dependence-analysis",
104 cl::desc(
"Which dependence analysis should loop fusion use?"),
106 "Use the scalar evolution interface"),
108 "Use the dependence analysis interface"),
110 "Use all available analyses")),
116 cl::desc(
"Enable verbose debugging for Loop Fusion"),
131 struct FusionCandidate {
168 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
169 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
170 Latch(L->getLoopLatch()), L(L), Valid(
true),
171 GuardBranch(L->getLoopGuardBranch()), DT(DT), PDT(PDT), ORE(ORE) {
178 if (BB->hasAddressTaken()) {
191 if (
SI->isVolatile()) {
197 if (
LoadInst *LI = dyn_cast<LoadInst>(&
I)) {
198 if (LI->isVolatile()) {
204 if (
I.mayWriteToMemory())
206 if (
I.mayReadFromMemory())
213 bool isValid()
const {
214 return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
220 assert(isValid() &&
"Candidate is not valid!!");
225 "Exiting Blocks is out of sync");
250 assert(GuardBranch &&
"Only valid on guarded loops.");
252 "Expecting guard to be a conditional branch.");
258 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 260 dbgs() <<
"\tGuardBranch: ";
262 dbgs() << *GuardBranch;
266 << (GuardBranch ? GuardBranch->
getName() :
"nullptr") <<
"\n" 267 <<
"\tPreheader: " << (Preheader ? Preheader->
getName() :
"nullptr")
269 <<
"\tHeader: " << (Header ? Header->
getName() :
"nullptr") <<
"\n" 271 << (ExitingBlock ? ExitingBlock->
getName() :
"nullptr") <<
"\n" 272 <<
"\tExitBB: " << (ExitBlock ? ExitBlock->
getName() :
"nullptr")
274 <<
"\tLatch: " << (Latch ? Latch->
getName() :
"nullptr") <<
"\n" 276 << (getEntryBlock() ? getEntryBlock()->getName() :
"nullptr")
292 ++InvalidExitingBlock;
306 <<
" trip count not computable!\n");
312 <<
" is not in simplified form!\n");
339 assert(L && Preheader &&
"Fusion candidate not initialized properly!");
344 <<
"Loop is not a candidate for fusion: " << Stat.
getDesc());
349 struct FusionCandidateCompare {
354 bool operator()(
const FusionCandidate &LHS,
355 const FusionCandidate &RHS)
const {
358 BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
359 BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
363 assert(DT && LHS.PDT &&
"Expecting valid dominator tree");
366 if (DT->
dominates(RHSEntryBlock, LHSEntryBlock)) {
369 assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
373 if (DT->
dominates(LHSEntryBlock, RHSEntryBlock)) {
375 assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
383 "No dominance relationship between these fusion candidates!");
399 using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
404 const FusionCandidate &
FC) {
406 OS << FC.Preheader->getName();
414 const FusionCandidateSet &CandSet) {
415 for (
const FusionCandidate &FC : CandSet)
422 printFusionCandidates(
const FusionCandidateCollection &FusionCandidates) {
423 dbgs() <<
"Fusion Candidates: \n";
424 for (
const auto &CandidateSet : FusionCandidates) {
425 dbgs() <<
"*** Fusion Candidate Set ***\n";
426 dbgs() << CandidateSet;
427 dbgs() <<
"****************************\n";
438 struct LoopDepthTree {
440 using iterator = LoopsOnLevelTy::iterator;
441 using const_iterator = LoopsOnLevelTy::const_iterator;
445 LoopsOnLevel.emplace_back(LoopVector(LI.
rbegin(), LI.
rend()));
450 bool isRemovedLoop(
const Loop *L)
const {
return RemovedLoops.count(L); }
454 void removeLoop(
const Loop *L) { RemovedLoops.insert(L); }
458 LoopsOnLevelTy LoopsOnNextLevel;
460 for (
const LoopVector &LV : *
this)
462 if (!isRemovedLoop(L) && L->
begin() != L->
end())
463 LoopsOnNextLevel.emplace_back(LoopVector(L->
begin(), L->
end()));
465 LoopsOnLevel = LoopsOnNextLevel;
466 RemovedLoops.clear();
470 bool empty()
const {
return size() == 0; }
471 size_t size()
const {
return LoopsOnLevel.size() - RemovedLoops.size(); }
474 iterator
begin() {
return LoopsOnLevel.
begin(); }
475 iterator
end() {
return LoopsOnLevel.
end(); }
476 const_iterator
begin()
const {
return LoopsOnLevel.
begin(); }
477 const_iterator
end()
const {
return LoopsOnLevel.
end(); }
488 LoopsOnLevelTy LoopsOnLevel;
492 static void printLoopVector(
const LoopVector &LV) {
493 dbgs() <<
"****************************\n";
496 dbgs() <<
"****************************\n";
503 FusionCandidateCollection FusionCandidates;
519 : LDT(LI), DTU(DT, PDT,
DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
520 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE) {}
534 bool Changed =
false;
536 while (!LDT.empty()) {
537 LLVM_DEBUG(
dbgs() <<
"Got " << LDT.size() <<
" loop sets for depth " 538 << LDT.getDepth() <<
"\n";);
540 for (
const LoopVector &LV : LDT) {
541 assert(LV.size() > 0 &&
"Empty loop set was build!");
550 dbgs() <<
" Visit loop set (#" << LV.size() <<
"):\n";
556 collectFusionCandidates(LV);
557 Changed |= fuseCandidates();
568 FusionCandidates.clear();
593 const FusionCandidate &FC1)
const {
594 assert(FC0.Preheader && FC1.Preheader &&
"Expecting valid preheaders");
603 void collectFusionCandidates(
const LoopVector &LV) {
605 FusionCandidate CurrCand(L, &DT, &PDT, ORE);
606 if (!CurrCand.isEligibleForFusion(SE))
614 bool FoundSet =
false;
616 for (
auto &CurrCandSet : FusionCandidates) {
618 CurrCandSet.insert(CurrCand);
623 <<
" to existing candidate set\n");
634 FusionCandidateSet NewCandSet;
635 NewCandSet.insert(CurrCand);
636 FusionCandidates.push_back(NewCandSet);
638 NumFusionCandidates++;
647 bool isBeneficialFusion(
const FusionCandidate &FC0,
648 const FusionCandidate &FC1) {
661 bool identicalTripCounts(
const FusionCandidate &FC0,
662 const FusionCandidate &FC1)
const {
664 if (isa<SCEVCouldNotCompute>(TripCount0)) {
665 UncomputableTripCount++;
666 LLVM_DEBUG(
dbgs() <<
"Trip count of first loop could not be computed!");
671 if (isa<SCEVCouldNotCompute>(TripCount1)) {
672 UncomputableTripCount++;
673 LLVM_DEBUG(
dbgs() <<
"Trip count of second loop could not be computed!");
677 << *TripCount1 <<
" are " 678 << (TripCount0 == TripCount1 ?
"identical" :
"different")
681 return (TripCount0 == TripCount1);
691 bool fuseCandidates() {
693 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
694 for (
auto &CandidateSet : FusionCandidates) {
695 if (CandidateSet.size() < 2)
699 << CandidateSet <<
"\n");
701 for (
auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
702 assert(!LDT.isRemovedLoop(FC0->L) &&
703 "Should not have removed loops in CandidateSet!");
705 for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
706 assert(!LDT.isRemovedLoop(FC1->L) &&
707 "Should not have removed loops in CandidateSet!");
709 LLVM_DEBUG(
dbgs() <<
"Attempting to fuse candidate \n"; FC0->dump();
710 dbgs() <<
" with\n"; FC1->dump();
dbgs() <<
"\n");
715 if (!identicalTripCounts(*FC0, *FC1)) {
716 LLVM_DEBUG(
dbgs() <<
"Fusion candidates do not have identical trip " 717 "counts. Not fusing.\n");
718 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
723 if (!isAdjacent(*FC0, *FC1)) {
725 <<
"Fusion candidates are not adjacent. Not fusing.\n");
726 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
732 if (FC0->GuardBranch && FC1->GuardBranch &&
733 !haveIdenticalGuards(*FC0, *FC1)) {
735 "guards. Not Fusing.\n");
736 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
746 if (!isEmptyPreheader(*FC1)) {
748 "preheader. Not fusing.\n");
749 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
754 if (FC0->GuardBranch && !isEmptyExitBlock(*FC0)) {
756 "block. Not fusing.\n");
757 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
762 if (FC1->GuardBranch && !isEmptyGuardBlock(*FC1)) {
763 LLVM_DEBUG(
dbgs() <<
"Fusion candidate does not have empty guard " 764 "block. Not fusing.\n");
765 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
772 if (!dependencesAllowFusion(*FC0, *FC1)) {
773 LLVM_DEBUG(
dbgs() <<
"Memory dependencies do not allow fusion!\n");
774 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
775 InvalidDependencies);
779 bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
781 <<
"\tFusion appears to be " 782 << (BeneficialToFuse ?
"" :
"un") <<
"profitable!\n");
783 if (!BeneficialToFuse) {
784 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
785 FusionNotBeneficial);
799 reportLoopFusion<OptimizationRemark>(*FC0, *FC1, FuseCounter);
801 FusionCandidate FusedCand(performFusion(*FC0, *FC1), &DT, &PDT, ORE);
803 assert(FusedCand.isEligibleForFusion(SE) &&
804 "Fused candidate should be eligible for fusion!");
807 LDT.removeLoop(FC1->L);
809 CandidateSet.erase(FC0);
810 CandidateSet.erase(FC1);
812 auto InsertPos = CandidateSet.insert(FusedCand);
814 assert(InsertPos.second &&
815 "Unable to insert TargetCandidate in CandidateSet!");
820 FC0 = FC1 = InsertPos.first;
822 LLVM_DEBUG(
dbgs() <<
"Candidate Set (after fusion): " << CandidateSet
843 if (ExprL == &OldL) {
848 if (OldL.contains(ExprL)) {
850 if (!UseMax || !Pos || !Expr->
isAffine()) {
862 bool wasValidSCEV()
const {
return Valid; }
866 const Loop &OldL, &NewL;
882 LLVM_DEBUG(
dbgs() <<
" Access function check: " << *SCEVPtr0 <<
" vs " 883 << *SCEVPtr1 <<
"\n");
885 AddRecLoopReplacer
Rewriter(SE, L0, L1);
886 SCEVPtr0 =
Rewriter.visit(SCEVPtr0);
889 LLVM_DEBUG(
dbgs() <<
" Access function after rewrite: " << *SCEVPtr0
890 <<
" [Valid: " <<
Rewriter.wasValidSCEV() <<
"]\n");
900 auto HasNonLinearDominanceRelation = [&](
const SCEV *S) {
916 << (IsAlwaysGE ?
" >= " :
" may < ") << *SCEVPtr1
925 bool dependencesAllowFusion(
const FusionCandidate &FC0,
932 << DepChoice <<
"\n");
937 return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
939 auto DepResult = DI.
depends(&I0, &I1,
true);
945 dbgs() <<
" [#l: " << DepResult->getLevels() <<
"][Ordered: " 946 << (DepResult->isOrdered() ?
"true" :
"false")
948 LLVM_DEBUG(
dbgs() <<
"DepResult Levels: " << DepResult->getLevels()
953 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
955 dbgs() <<
"TODO: Implement pred/succ dependence handling!\n");
962 return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
964 dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
972 bool dependencesAllowFusion(
const FusionCandidate &FC0,
973 const FusionCandidate &FC1) {
974 LLVM_DEBUG(
dbgs() <<
"Check if " << FC0 <<
" can be fused with " << FC1
976 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
981 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
984 InvalidDependencies++;
988 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
991 InvalidDependencies++;
998 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1001 InvalidDependencies++;
1005 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
1008 InvalidDependencies++;
1017 for (
auto &
Op :
I.operands())
1019 if (FC0.L->contains(
Def->getParent())) {
1020 InvalidDependencies++;
1036 bool isAdjacent(
const FusionCandidate &FC0,
1037 const FusionCandidate &FC1)
const {
1039 if (FC0.GuardBranch)
1040 return FC0.getNonLoopBlock() == FC1.getEntryBlock();
1042 return FC0.ExitBlock == FC1.getEntryBlock();
1057 bool haveIdenticalGuards(
const FusionCandidate &FC0,
1058 const FusionCandidate &FC1)
const {
1059 assert(FC0.GuardBranch && FC1.GuardBranch &&
1060 "Expecting FC0 and FC1 to be guarded loops.");
1062 if (
auto FC0CmpInst =
1063 dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
1064 if (
auto FC1CmpInst =
1065 dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
1066 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1072 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1073 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1075 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1083 bool isEmptyGuardBlock(
const FusionCandidate &FC)
const {
1084 assert(FC.GuardBranch &&
"Expecting a fusion candidate with guard branch.");
1085 if (
auto *
CmpInst = dyn_cast<Instruction>(FC.GuardBranch->getCondition())) {
1086 auto *GuardBlock = FC.GuardBranch->getParent();
1092 return GuardBlock->size() == 2;
1094 return GuardBlock->size() == 1;
1100 bool isEmptyPreheader(
const FusionCandidate &FC)
const {
1101 assert(FC.Preheader &&
"Expecting a valid preheader");
1102 return FC.Preheader->size() == 1;
1105 bool isEmptyExitBlock(
const FusionCandidate &FC)
const {
1106 assert(FC.ExitBlock &&
"Expecting a valid exit block");
1107 return FC.ExitBlock->size() == 1;
1112 void simplifyLatchBranch(
const FusionCandidate &FC)
const {
1114 if (FCLatchBranch) {
1117 "Expecting the two successors of FCLatchBranch to be the same");
1125 void mergeLatch(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1127 if (
BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
1162 Loop *performFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1) {
1163 assert(FC0.isValid() && FC1.isValid() &&
1164 "Expecting valid fusion candidates");
1167 dbgs() <<
"Fusion Candidate 1: \n"; FC1.dump(););
1172 if (FC0.GuardBranch)
1173 return fuseGuardedLoops(FC0, FC1);
1175 assert(FC1.Preheader == FC0.ExitBlock);
1176 assert(FC1.Preheader->size() == 1 &&
1177 FC1.Preheader->getSingleSuccessor() == FC1.Header);
1189 if (FC0.ExitingBlock != FC0.Latch)
1190 for (
PHINode &PHI : FC0.Header->phis())
1194 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1195 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1217 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1226 FC1.Preheader->getTerminator()->eraseFromParent();
1232 while (
PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1235 if (PHI->hasNUsesOrMore(1))
1236 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1238 PHI->eraseFromParent();
1246 for (
PHINode *LCPHI : OriginalFC0PHIs) {
1247 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1248 assert(L1LatchBBIdx >= 0 &&
1249 "Expected loop carried value to be rewired at this point!");
1251 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1254 LCV->
getType(), 2, LCPHI->getName() +
".afterFC0", L1HeaderIP);
1259 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1263 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1264 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1268 simplifyLatchBranch(FC0);
1272 if (FC0.Latch != FC0.ExitingBlock)
1277 FC0.Latch, FC0.Header));
1279 FC1.Latch, FC0.Header));
1281 FC1.Latch, FC1.Header));
1299 mergeLatch(FC0, FC1);
1303 FC1.L->block_end());
1305 FC0.L->addBlockEntry(BB);
1306 FC1.L->removeBlockFromLoop(BB);
1311 while (!FC1.L->empty()) {
1312 const auto &ChildLoopIt = FC1.L->begin();
1313 Loop *ChildLoop = *ChildLoopIt;
1314 FC1.L->removeChildLoop(ChildLoopIt);
1315 FC0.L->addChildLoop(ChildLoop);
1346 template <
typename RemarkKind>
1347 void reportLoopFusion(
const FusionCandidate &FC0,
const FusionCandidate &FC1,
1349 assert(FC0.Preheader && FC1.Preheader &&
1350 "Expecting valid fusion candidates");
1351 using namespace ore;
1355 <<
"[" << FC0.Preheader->getParent()->getName()
1356 <<
"]: " <<
NV(
"Cand1",
StringRef(FC0.Preheader->getName()))
1357 <<
" and " <<
NV(
"Cand2",
StringRef(FC1.Preheader->getName()))
1376 Loop *fuseGuardedLoops(
const FusionCandidate &FC0,
1377 const FusionCandidate &FC1) {
1378 assert(FC0.GuardBranch && FC1.GuardBranch &&
"Expecting guarded loops");
1380 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1381 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1382 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1383 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1385 assert(FC0NonLoopBlock == FC1GuardBlock &&
"Loops are not adjacent");
1397 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1398 FC0.ExitBlock->getTerminator()->replaceUsesOfWith(FC1GuardBlock,
1402 FC1.GuardBranch->eraseFromParent();
1415 "Expecting guard block to have no predecessors");
1417 "Expecting guard block to have no successors");
1432 if (FC0.ExitingBlock != FC0.Latch)
1433 for (
PHINode &PHI : FC0.Header->phis())
1436 assert(OriginalFC0PHIs.
empty() &&
"Expecting OriginalFC0PHIs to be empty!");
1439 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1440 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1455 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1471 "Expecting exit block to be empty");
1472 FC0.ExitBlock->getTerminator()->eraseFromParent();
1478 FC1.Preheader->getTerminator()->eraseFromParent();
1484 while (
PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1487 if (PHI->hasNUsesOrMore(1))
1488 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1490 PHI->eraseFromParent();
1498 for (
PHINode *LCPHI : OriginalFC0PHIs) {
1499 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1500 assert(L1LatchBBIdx >= 0 &&
1501 "Expected loop carried value to be rewired at this point!");
1503 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1506 LCV->
getType(), 2, LCPHI->getName() +
".afterFC0", L1HeaderIP);
1511 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1517 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1518 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1522 simplifyLatchBranch(FC0);
1526 if (FC0.Latch != FC0.ExitingBlock)
1531 FC0.Latch, FC0.Header));
1533 FC1.Latch, FC0.Header));
1535 FC1.Latch, FC1.Header));
1541 "FC1GuardBlock has successors!!");
1543 "FC1GuardBlock has predecessors!!");
1562 mergeLatch(FC0, FC1);
1566 FC1.L->block_end());
1568 FC0.L->addBlockEntry(BB);
1569 FC1.L->removeBlockFromLoop(BB);
1574 while (!FC1.L->empty()) {
1575 const auto &ChildLoopIt = FC1.L->begin();
1576 Loop *ChildLoop = *ChildLoopIt;
1577 FC1.L->removeChildLoop(ChildLoopIt);
1578 FC0.L->addChildLoop(ChildLoop);
1622 if (skipFunction(F))
1624 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1625 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1626 auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1627 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1628 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1629 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1632 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1633 return LF.fuseLoops(F);
1647 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1648 bool Changed = LF.fuseLoops(F);
void initializeLoopFuseLegacyPass(PassRegistry &)
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
reference emplace_back(ArgTypes &&... Args)
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisPass to compute dependence information in a function.
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Legacy pass manager pass to access dependence information.
void push_back(const T &Elt)
The main scalar evolution driver.
bool isRotatedForm() const
Return true if the loop is in rotated form.
This file implements the Loop Fusion pass.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void moveInstsBottomUp(BasicBlock &FromBB, BasicBlock &ToBB, const DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI)
Move instructions from FromBB bottom up to the beginning of ToBB when proven safe.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
Analysis pass which computes a DominatorTree.
block Block Frequency true
An instruction for reading from memory.
Value * getCondition() const
INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false) FunctionPass *llvm
DependenceInfo - This class is the main dependence-analysis driver.
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isInvalid() const
Return true if this loop is no longer valid.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
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), cl::ZeroOrMore)
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
void dump() const
Support for debugging, callable in GDB: V->dump()
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static cl::opt< bool > VerboseFusionDebugging("loop-fusion-verbose-debug", cl::desc("Enable verbose debugging for Loop Fusion"), cl::Hidden, cl::init(false), cl::ZeroOrMore)
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
const char * getName() const
Analysis pass that exposes the LoopInfo for a function.
const char * getDesc() const
mir Rename Register Operands
cfg::Update< NodePtr > UpdateType
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
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...
op_range operands() const
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isControlFlowEquivalent(const Instruction &I0, const Instruction &I1, const DominatorTree &DT, const PostDominatorTree &PDT)
Return true if I0 and I1 are control flow equivalent.
An instruction for storing to memory.
op_iterator op_begin() const
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
Interval::succ_iterator succ_end(Interval *I)
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
friend const_iterator end(StringRef path)
Get end iterator over path.
std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool PossiblyLoopIndependent)
depends - Tests for a dependence between the Src and Dst instructions.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
Represent the analysis usage information of a pass.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
op_iterator op_end() const
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
const SCEV * getStart() const
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...
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void print(raw_ostream &OS) const
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
AnalysisUsage & addRequiredID(const void *ID)
reverse_iterator rend() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Analysis pass which computes a PostDominatorTree.
static unsigned getDepth(const SmallVectorImpl< const MachineBasicBlock *> &Stack, const MachineBasicBlock *MBB)
bool isConditional() const
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...
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
reverse_iterator rbegin() const
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
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...
FunctionPass * createLoopFusePass()
Analysis pass that exposes the ScalarEvolution for a function.
Virtual Register Rewriter
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
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...
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
void preserve()
Mark an analysis as preserved.
FusionDependenceAnalysisChoice
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
void setCondition(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
This class implements an extremely fast bulk output stream that can only output to a stream...
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
iterator_range< block_iterator > blocks() const
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
This visitor recursively visits a SCEV expression and re-writes it.
const BasicBlock * getParent() const