1 //===- LoopFuse.cpp - Loop Fusion Pass ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the loop fusion pass.
11 /// The implementation is largely based on the following document:
12 ///
13 ///       Code Transformations to Augment the Scope of Loop Fusion in a
14 ///         Production Compiler
15 ///       Christopher Mark Barton
16 ///       MSc Thesis
17 ///       https://webdocs.cs.ualberta.ca/~amaral/thesis/ChristopherBartonMSc.pdf
18 ///
19 /// The general approach taken is to collect sets of control flow equivalent
20 /// loops and test whether they can be fused. The necessary conditions for
21 /// fusion are:
22 ///    1. The loops must be adjacent (there cannot be any statements between
23 ///       the two loops).
24 ///    2. The loops must be conforming (they must execute the same number of
25 ///       iterations).
26 ///    3. The loops must be control flow equivalent (if one loop executes, the
27 ///       other is guaranteed to execute).
28 ///    4. There cannot be any negative distance dependencies between the loops.
29 /// If all of these conditions are satisfied, it is safe to fuse the loops.
30 ///
31 /// This implementation creates FusionCandidates that represent the loop and the
32 /// necessary information needed by fusion. It then operates on the fusion
33 /// candidates, first confirming that the candidate is eligible for fusion. The
34 /// candidates are then collected into control flow equivalent sets, sorted in
35 /// dominance order. Each set of control flow equivalent candidates is then
36 /// traversed, attempting to fuse pairs of candidates in the set. If all
37 /// requirements for fusion are met, the two candidates are fused, creating a
38 /// new (fused) candidate which is then added back into the set to consider for
39 /// additional fusion.
40 ///
41 /// This implementation currently does not make any modifications to remove
42 /// conditions for fusion. Code transformations to make loops conform to each of
43 /// the conditions for fusion are discussed in more detail in the document
44 /// above. These can be added to the current implementation in the future.
45 //===----------------------------------------------------------------------===//
46 
47 #include "llvm/Transforms/Scalar/LoopFuse.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Analysis/DependenceAnalysis.h"
50 #include "llvm/Analysis/DomTreeUpdater.h"
51 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
53 #include "llvm/Analysis/PostDominators.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/Verifier.h"
58 #include "llvm/InitializePasses.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Utils.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/CodeMoverUtils.h"
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "loop-fusion"
71 
72 STATISTIC(FuseCounter, "Loops fused");
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");
95 
96 enum FusionDependenceAnalysisChoice {
97   FUSION_DEPENDENCE_ANALYSIS_SCEV,
98   FUSION_DEPENDENCE_ANALYSIS_DA,
99   FUSION_DEPENDENCE_ANALYSIS_ALL,
100 };
101 
102 static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis(
103     "loop-fusion-dependence-analysis",
104     cl::desc("Which dependence analysis should loop fusion use?"),
105     cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev",
106                           "Use the scalar evolution interface"),
107                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da",
108                           "Use the dependence analysis interface"),
109                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all",
110                           "Use all available analyses")),
111     cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore);
112 
113 #ifndef NDEBUG
114 static cl::opt<bool>
115     VerboseFusionDebugging("loop-fusion-verbose-debug",
116                            cl::desc("Enable verbose debugging for Loop Fusion"),
117                            cl::Hidden, cl::init(false), cl::ZeroOrMore);
118 #endif
119 
120 namespace {
121 /// This class is used to represent a candidate for loop fusion. When it is
122 /// constructed, it checks the conditions for loop fusion to ensure that it
123 /// represents a valid candidate. It caches several parts of a loop that are
124 /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
125 /// of continually querying the underlying Loop to retrieve these values. It is
126 /// assumed these will not change throughout loop fusion.
127 ///
128 /// The invalidate method should be used to indicate that the FusionCandidate is
129 /// no longer a valid candidate for fusion. Similarly, the isValid() method can
130 /// be used to ensure that the FusionCandidate is still valid for fusion.
131 struct FusionCandidate {
132   /// Cache of parts of the loop used throughout loop fusion. These should not
133   /// need to change throughout the analysis and transformation.
134   /// These parts are cached to avoid repeatedly looking up in the Loop class.
135 
136   /// Preheader of the loop this candidate represents
137   BasicBlock *Preheader;
138   /// Header of the loop this candidate represents
139   BasicBlock *Header;
140   /// Blocks in the loop that exit the loop
141   BasicBlock *ExitingBlock;
142   /// The successor block of this loop (where the exiting blocks go to)
143   BasicBlock *ExitBlock;
144   /// Latch of the loop
145   BasicBlock *Latch;
146   /// The loop that this fusion candidate represents
147   Loop *L;
148   /// Vector of instructions in this loop that read from memory
149   SmallVector<Instruction *, 16> MemReads;
150   /// Vector of instructions in this loop that write to memory
151   SmallVector<Instruction *, 16> MemWrites;
152   /// Are all of the members of this fusion candidate still valid
153   bool Valid;
154   /// Guard branch of the loop, if it exists
155   BranchInst *GuardBranch;
156 
157   /// Dominator and PostDominator trees are needed for the
158   /// FusionCandidateCompare function, required by FusionCandidateSet to
159   /// determine where the FusionCandidate should be inserted into the set. These
160   /// are used to establish ordering of the FusionCandidates based on dominance.
161   const DominatorTree *DT;
162   const PostDominatorTree *PDT;
163 
164   OptimizationRemarkEmitter &ORE;
165 
166   FusionCandidate(Loop *L, const DominatorTree *DT,
167                   const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE)
168       : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
169         ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
170         Latch(L->getLoopLatch()), L(L), Valid(true), GuardBranch(nullptr),
171         DT(DT), PDT(PDT), ORE(ORE) {
172 
173     // TODO: This is temporary while we fuse both rotated and non-rotated
174     // loops. Once we switch to only fusing rotated loops, the initialization of
175     // GuardBranch can be moved into the initialization list above.
176     if (isRotated())
177       GuardBranch = L->getLoopGuardBranch();
178 
179     // Walk over all blocks in the loop and check for conditions that may
180     // prevent fusion. For each block, walk over all instructions and collect
181     // the memory reads and writes If any instructions that prevent fusion are
182     // found, invalidate this object and return.
183     for (BasicBlock *BB : L->blocks()) {
184       if (BB->hasAddressTaken()) {
185         invalidate();
186         reportInvalidCandidate(AddressTakenBB);
187         return;
188       }
189 
190       for (Instruction &I : *BB) {
191         if (I.mayThrow()) {
192           invalidate();
193           reportInvalidCandidate(MayThrowException);
194           return;
195         }
196         if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
197           if (SI->isVolatile()) {
198             invalidate();
199             reportInvalidCandidate(ContainsVolatileAccess);
200             return;
201           }
202         }
203         if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
204           if (LI->isVolatile()) {
205             invalidate();
206             reportInvalidCandidate(ContainsVolatileAccess);
207             return;
208           }
209         }
210         if (I.mayWriteToMemory())
211           MemWrites.push_back(&I);
212         if (I.mayReadFromMemory())
213           MemReads.push_back(&I);
214       }
215     }
216   }
217 
218   /// Check if all members of the class are valid.
219   bool isValid() const {
220     return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
221            !L->isInvalid() && Valid;
222   }
223 
224   /// Verify that all members are in sync with the Loop object.
225   void verify() const {
226     assert(isValid() && "Candidate is not valid!!");
227     assert(!L->isInvalid() && "Loop is invalid!");
228     assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
229     assert(Header == L->getHeader() && "Header is out of sync");
230     assert(ExitingBlock == L->getExitingBlock() &&
231            "Exiting Blocks is out of sync");
232     assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
233     assert(Latch == L->getLoopLatch() && "Latch is out of sync");
234   }
235 
236   /// Get the entry block for this fusion candidate.
237   ///
238   /// If this fusion candidate represents a guarded loop, the entry block is the
239   /// loop guard block. If it represents an unguarded loop, the entry block is
240   /// the preheader of the loop.
241   BasicBlock *getEntryBlock() const {
242     if (GuardBranch)
243       return GuardBranch->getParent();
244     else
245       return Preheader;
246   }
247 
248   /// Given a guarded loop, get the successor of the guard that is not in the
249   /// loop.
250   ///
251   /// This method returns the successor of the loop guard that is not located
252   /// within the loop (i.e., the successor of the guard that is not the
253   /// preheader).
254   /// This method is only valid for guarded loops.
255   BasicBlock *getNonLoopBlock() const {
256     assert(GuardBranch && "Only valid on guarded loops.");
257     assert(GuardBranch->isConditional() &&
258            "Expecting guard to be a conditional branch.");
259     return (GuardBranch->getSuccessor(0) == Preheader)
260                ? GuardBranch->getSuccessor(1)
261                : GuardBranch->getSuccessor(0);
262   }
263 
264   bool isRotated() const {
265     assert(L && "Expecting loop to be valid.");
266     assert(Latch && "Expecting latch to be valid.");
267     return L->isLoopExiting(Latch);
268   }
269 
270 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
271   LLVM_DUMP_METHOD void dump() const {
272     dbgs() << "\tGuardBranch: "
273            << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
274            << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
275            << "\n"
276            << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
277            << "\tExitingBB: "
278            << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
279            << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
280            << "\n"
281            << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
282            << "\tEntryBlock: "
283            << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
284            << "\n";
285   }
286 #endif
287 
288   /// Determine if a fusion candidate (representing a loop) is eligible for
289   /// fusion. Note that this only checks whether a single loop can be fused - it
290   /// does not check whether it is *legal* to fuse two loops together.
291   bool isEligibleForFusion(ScalarEvolution &SE) const {
292     if (!isValid()) {
293       LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
294       if (!Preheader)
295         ++InvalidPreheader;
296       if (!Header)
297         ++InvalidHeader;
298       if (!ExitingBlock)
299         ++InvalidExitingBlock;
300       if (!ExitBlock)
301         ++InvalidExitBlock;
302       if (!Latch)
303         ++InvalidLatch;
304       if (L->isInvalid())
305         ++InvalidLoop;
306 
307       return false;
308     }
309 
310     // Require ScalarEvolution to be able to determine a trip count.
311     if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
312       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
313                         << " trip count not computable!\n");
314       return reportInvalidCandidate(UnknownTripCount);
315     }
316 
317     if (!L->isLoopSimplifyForm()) {
318       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
319                         << " is not in simplified form!\n");
320       return reportInvalidCandidate(NotSimplifiedForm);
321     }
322 
323     if (!isRotated()) {
324       LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
325       return reportInvalidCandidate(NotRotated);
326     }
327 
328     return true;
329   }
330 
331 private:
332   // This is only used internally for now, to clear the MemWrites and MemReads
333   // list and setting Valid to false. I can't envision other uses of this right
334   // now, since once FusionCandidates are put into the FusionCandidateSet they
335   // are immutable. Thus, any time we need to change/update a FusionCandidate,
336   // we must create a new one and insert it into the FusionCandidateSet to
337   // ensure the FusionCandidateSet remains ordered correctly.
338   void invalidate() {
339     MemWrites.clear();
340     MemReads.clear();
341     Valid = false;
342   }
343 
344   bool reportInvalidCandidate(llvm::Statistic &Stat) const {
345     using namespace ore;
346     assert(L && Preheader && "Fusion candidate not initialized properly!");
347     ++Stat;
348     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
349                                         L->getStartLoc(), Preheader)
350              << "[" << Preheader->getParent()->getName() << "]: "
351              << "Loop is not a candidate for fusion: " << Stat.getDesc());
352     return false;
353   }
354 };
355 
356 struct FusionCandidateCompare {
357   /// Comparison functor to sort two Control Flow Equivalent fusion candidates
358   /// into dominance order.
359   /// If LHS dominates RHS and RHS post-dominates LHS, return true;
360   /// IF RHS dominates LHS and LHS post-dominates RHS, return false;
361   bool operator()(const FusionCandidate &LHS,
362                   const FusionCandidate &RHS) const {
363     const DominatorTree *DT = LHS.DT;
364 
365     BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
366     BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
367 
368     // Do not save PDT to local variable as it is only used in asserts and thus
369     // will trigger an unused variable warning if building without asserts.
370     assert(DT && LHS.PDT && "Expecting valid dominator tree");
371 
372     // Do this compare first so if LHS == RHS, function returns false.
373     if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
374       // RHS dominates LHS
375       // Verify LHS post-dominates RHS
376       assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
377       return false;
378     }
379 
380     if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
381       // Verify RHS Postdominates LHS
382       assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
383       return true;
384     }
385 
386     // If LHS does not dominate RHS and RHS does not dominate LHS then there is
387     // no dominance relationship between the two FusionCandidates. Thus, they
388     // should not be in the same set together.
389     llvm_unreachable(
390         "No dominance relationship between these fusion candidates!");
391   }
392 };
393 
394 using LoopVector = SmallVector<Loop *, 4>;
395 
396 // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
397 // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
398 // dominates FC1 and FC1 post-dominates FC0.
399 // std::set was chosen because we want a sorted data structure with stable
400 // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
401 // loops by moving intervening code around. When this intervening code contains
402 // loops, those loops will be moved also. The corresponding FusionCandidates
403 // will also need to be moved accordingly. As this is done, having stable
404 // iterators will simplify the logic. Similarly, having an efficient insert that
405 // keeps the FusionCandidateSet sorted will also simplify the implementation.
406 using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
407 using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
408 
409 #if !defined(NDEBUG)
410 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
411                                      const FusionCandidate &FC) {
412   if (FC.isValid())
413     OS << FC.Preheader->getName();
414   else
415     OS << "<Invalid>";
416 
417   return OS;
418 }
419 
420 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
421                                      const FusionCandidateSet &CandSet) {
422   for (const FusionCandidate &FC : CandSet)
423     OS << FC << '\n';
424 
425   return OS;
426 }
427 
428 static void
429 printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
430   dbgs() << "Fusion Candidates: \n";
431   for (const auto &CandidateSet : FusionCandidates) {
432     dbgs() << "*** Fusion Candidate Set ***\n";
433     dbgs() << CandidateSet;
434     dbgs() << "****************************\n";
435   }
436 }
437 #endif
438 
439 /// Collect all loops in function at the same nest level, starting at the
440 /// outermost level.
441 ///
442 /// This data structure collects all loops at the same nest level for a
443 /// given function (specified by the LoopInfo object). It starts at the
444 /// outermost level.
445 struct LoopDepthTree {
446   using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
447   using iterator = LoopsOnLevelTy::iterator;
448   using const_iterator = LoopsOnLevelTy::const_iterator;
449 
450   LoopDepthTree(LoopInfo &LI) : Depth(1) {
451     if (!LI.empty())
452       LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
453   }
454 
455   /// Test whether a given loop has been removed from the function, and thus is
456   /// no longer valid.
457   bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
458 
459   /// Record that a given loop has been removed from the function and is no
460   /// longer valid.
461   void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
462 
463   /// Descend the tree to the next (inner) nesting level
464   void descend() {
465     LoopsOnLevelTy LoopsOnNextLevel;
466 
467     for (const LoopVector &LV : *this)
468       for (Loop *L : LV)
469         if (!isRemovedLoop(L) && L->begin() != L->end())
470           LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
471 
472     LoopsOnLevel = LoopsOnNextLevel;
473     RemovedLoops.clear();
474     Depth++;
475   }
476 
477   bool empty() const { return size() == 0; }
478   size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
479   unsigned getDepth() const { return Depth; }
480 
481   iterator begin() { return LoopsOnLevel.begin(); }
482   iterator end() { return LoopsOnLevel.end(); }
483   const_iterator begin() const { return LoopsOnLevel.begin(); }
484   const_iterator end() const { return LoopsOnLevel.end(); }
485 
486 private:
487   /// Set of loops that have been removed from the function and are no longer
488   /// valid.
489   SmallPtrSet<const Loop *, 8> RemovedLoops;
490 
491   /// Depth of the current level, starting at 1 (outermost loops).
492   unsigned Depth;
493 
494   /// Vector of loops at the current depth level that have the same parent loop
495   LoopsOnLevelTy LoopsOnLevel;
496 };
497 
498 #ifndef NDEBUG
499 static void printLoopVector(const LoopVector &LV) {
500   dbgs() << "****************************\n";
501   for (auto L : LV)
502     printLoop(*L, dbgs());
503   dbgs() << "****************************\n";
504 }
505 #endif
506 
507 struct LoopFuser {
508 private:
509   // Sets of control flow equivalent fusion candidates for a given nest level.
510   FusionCandidateCollection FusionCandidates;
511 
512   LoopDepthTree LDT;
513   DomTreeUpdater DTU;
514 
515   LoopInfo &LI;
516   DominatorTree &DT;
517   DependenceInfo &DI;
518   ScalarEvolution &SE;
519   PostDominatorTree &PDT;
520   OptimizationRemarkEmitter &ORE;
521 
522 public:
523   LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
524             ScalarEvolution &SE, PostDominatorTree &PDT,
525             OptimizationRemarkEmitter &ORE, const DataLayout &DL)
526       : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
527         DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE) {}
528 
529   /// This is the main entry point for loop fusion. It will traverse the
530   /// specified function and collect candidate loops to fuse, starting at the
531   /// outermost nesting level and working inwards.
532   bool fuseLoops(Function &F) {
533 #ifndef NDEBUG
534     if (VerboseFusionDebugging) {
535       LI.print(dbgs());
536     }
537 #endif
538 
539     LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
540                       << "\n");
541     bool Changed = false;
542 
543     while (!LDT.empty()) {
544       LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
545                         << LDT.getDepth() << "\n";);
546 
547       for (const LoopVector &LV : LDT) {
548         assert(LV.size() > 0 && "Empty loop set was build!");
549 
550         // Skip singleton loop sets as they do not offer fusion opportunities on
551         // this level.
552         if (LV.size() == 1)
553           continue;
554 #ifndef NDEBUG
555         if (VerboseFusionDebugging) {
556           LLVM_DEBUG({
557             dbgs() << "  Visit loop set (#" << LV.size() << "):\n";
558             printLoopVector(LV);
559           });
560         }
561 #endif
562 
563         collectFusionCandidates(LV);
564         Changed |= fuseCandidates();
565       }
566 
567       // Finished analyzing candidates at this level.
568       // Descend to the next level and clear all of the candidates currently
569       // collected. Note that it will not be possible to fuse any of the
570       // existing candidates with new candidates because the new candidates will
571       // be at a different nest level and thus not be control flow equivalent
572       // with all of the candidates collected so far.
573       LLVM_DEBUG(dbgs() << "Descend one level!\n");
574       LDT.descend();
575       FusionCandidates.clear();
576     }
577 
578     if (Changed)
579       LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
580 
581 #ifndef NDEBUG
582     assert(DT.verify());
583     assert(PDT.verify());
584     LI.verify(DT);
585     SE.verify();
586 #endif
587 
588     LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
589     return Changed;
590   }
591 
592 private:
593   /// Determine if two fusion candidates are control flow equivalent.
594   ///
595   /// Two fusion candidates are control flow equivalent if when one executes,
596   /// the other is guaranteed to execute. This is determined using dominators
597   /// and post-dominators: if A dominates B and B post-dominates A then A and B
598   /// are control-flow equivalent.
599   bool isControlFlowEquivalent(const FusionCandidate &FC0,
600                                const FusionCandidate &FC1) const {
601     assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
602 
603     return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
604                                      DT, PDT);
605   }
606 
607   /// Iterate over all loops in the given loop set and identify the loops that
608   /// are eligible for fusion. Place all eligible fusion candidates into Control
609   /// Flow Equivalent sets, sorted by dominance.
610   void collectFusionCandidates(const LoopVector &LV) {
611     for (Loop *L : LV) {
612       FusionCandidate CurrCand(L, &DT, &PDT, ORE);
613       if (!CurrCand.isEligibleForFusion(SE))
614         continue;
615 
616       // Go through each list in FusionCandidates and determine if L is control
617       // flow equivalent with the first loop in that list. If it is, append LV.
618       // If not, go to the next list.
619       // If no suitable list is found, start another list and add it to
620       // FusionCandidates.
621       bool FoundSet = false;
622 
623       for (auto &CurrCandSet : FusionCandidates) {
624         if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
625           CurrCandSet.insert(CurrCand);
626           FoundSet = true;
627 #ifndef NDEBUG
628           if (VerboseFusionDebugging)
629             LLVM_DEBUG(dbgs() << "Adding " << CurrCand
630                               << " to existing candidate set\n");
631 #endif
632           break;
633         }
634       }
635       if (!FoundSet) {
636         // No set was found. Create a new set and add to FusionCandidates
637 #ifndef NDEBUG
638         if (VerboseFusionDebugging)
639           LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
640 #endif
641         FusionCandidateSet NewCandSet;
642         NewCandSet.insert(CurrCand);
643         FusionCandidates.push_back(NewCandSet);
644       }
645       NumFusionCandidates++;
646     }
647   }
648 
649   /// Determine if it is beneficial to fuse two loops.
650   ///
651   /// For now, this method simply returns true because we want to fuse as much
652   /// as possible (primarily to test the pass). This method will evolve, over
653   /// time, to add heuristics for profitability of fusion.
654   bool isBeneficialFusion(const FusionCandidate &FC0,
655                           const FusionCandidate &FC1) {
656     return true;
657   }
658 
659   /// Determine if two fusion candidates have the same trip count (i.e., they
660   /// execute the same number of iterations).
661   ///
662   /// Note that for now this method simply returns a boolean value because there
663   /// are no mechanisms in loop fusion to handle different trip counts. In the
664   /// future, this behaviour can be extended to adjust one of the loops to make
665   /// the trip counts equal (e.g., loop peeling). When this is added, this
666   /// interface may need to change to return more information than just a
667   /// boolean value.
668   bool identicalTripCounts(const FusionCandidate &FC0,
669                            const FusionCandidate &FC1) const {
670     const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
671     if (isa<SCEVCouldNotCompute>(TripCount0)) {
672       UncomputableTripCount++;
673       LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
674       return false;
675     }
676 
677     const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
678     if (isa<SCEVCouldNotCompute>(TripCount1)) {
679       UncomputableTripCount++;
680       LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
681       return false;
682     }
683     LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
684                       << *TripCount1 << " are "
685                       << (TripCount0 == TripCount1 ? "identical" : "different")
686                       << "\n");
687 
688     return (TripCount0 == TripCount1);
689   }
690 
691   /// Walk each set of control flow equivalent fusion candidates and attempt to
692   /// fuse them. This does a single linear traversal of all candidates in the
693   /// set. The conditions for legal fusion are checked at this point. If a pair
694   /// of fusion candidates passes all legality checks, they are fused together
695   /// and a new fusion candidate is created and added to the FusionCandidateSet.
696   /// The original fusion candidates are then removed, as they are no longer
697   /// valid.
698   bool fuseCandidates() {
699     bool Fused = false;
700     LLVM_DEBUG(printFusionCandidates(FusionCandidates));
701     for (auto &CandidateSet : FusionCandidates) {
702       if (CandidateSet.size() < 2)
703         continue;
704 
705       LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
706                         << CandidateSet << "\n");
707 
708       for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
709         assert(!LDT.isRemovedLoop(FC0->L) &&
710                "Should not have removed loops in CandidateSet!");
711         auto FC1 = FC0;
712         for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
713           assert(!LDT.isRemovedLoop(FC1->L) &&
714                  "Should not have removed loops in CandidateSet!");
715 
716           LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
717                      dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
718 
719           FC0->verify();
720           FC1->verify();
721 
722           if (!identicalTripCounts(*FC0, *FC1)) {
723             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
724                                  "counts. Not fusing.\n");
725             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
726                                                        NonEqualTripCount);
727             continue;
728           }
729 
730           if (!isAdjacent(*FC0, *FC1)) {
731             LLVM_DEBUG(dbgs()
732                        << "Fusion candidates are not adjacent. Not fusing.\n");
733             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
734             continue;
735           }
736 
737           // Ensure that FC0 and FC1 have identical guards.
738           // If one (or both) are not guarded, this check is not necessary.
739           if (FC0->GuardBranch && FC1->GuardBranch &&
740               !haveIdenticalGuards(*FC0, *FC1)) {
741             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
742                                  "guards. Not Fusing.\n");
743             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
744                                                        NonIdenticalGuards);
745             continue;
746           }
747 
748           // The following three checks look for empty blocks in FC0 and FC1. If
749           // any of these blocks are non-empty, we do not fuse. This is done
750           // because we currently do not have the safety checks to determine if
751           // it is safe to move the blocks past other blocks in the loop. Once
752           // these checks are added, these conditions can be relaxed.
753           if (!isEmptyPreheader(*FC1)) {
754             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
755                                  "preheader. Not fusing.\n");
756             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
757                                                        NonEmptyPreheader);
758             continue;
759           }
760 
761           if (FC0->GuardBranch && !isEmptyExitBlock(*FC0)) {
762             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty exit "
763                                  "block. Not fusing.\n");
764             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
765                                                        NonEmptyExitBlock);
766             continue;
767           }
768 
769           if (FC1->GuardBranch && !isEmptyGuardBlock(*FC1)) {
770             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty guard "
771                                  "block. Not fusing.\n");
772             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
773                                                        NonEmptyGuardBlock);
774             continue;
775           }
776 
777           // Check the dependencies across the loops and do not fuse if it would
778           // violate them.
779           if (!dependencesAllowFusion(*FC0, *FC1)) {
780             LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
781             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
782                                                        InvalidDependencies);
783             continue;
784           }
785 
786           bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
787           LLVM_DEBUG(dbgs()
788                      << "\tFusion appears to be "
789                      << (BeneficialToFuse ? "" : "un") << "profitable!\n");
790           if (!BeneficialToFuse) {
791             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
792                                                        FusionNotBeneficial);
793             continue;
794           }
795           // All analysis has completed and has determined that fusion is legal
796           // and profitable. At this point, start transforming the code and
797           // perform fusion.
798 
799           LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
800                             << *FC1 << "\n");
801 
802           // Report fusion to the Optimization Remarks.
803           // Note this needs to be done *before* performFusion because
804           // performFusion will change the original loops, making it not
805           // possible to identify them after fusion is complete.
806           reportLoopFusion<OptimizationRemark>(*FC0, *FC1, FuseCounter);
807 
808           FusionCandidate FusedCand(performFusion(*FC0, *FC1), &DT, &PDT, ORE);
809           FusedCand.verify();
810           assert(FusedCand.isEligibleForFusion(SE) &&
811                  "Fused candidate should be eligible for fusion!");
812 
813           // Notify the loop-depth-tree that these loops are not valid objects
814           LDT.removeLoop(FC1->L);
815 
816           CandidateSet.erase(FC0);
817           CandidateSet.erase(FC1);
818 
819           auto InsertPos = CandidateSet.insert(FusedCand);
820 
821           assert(InsertPos.second &&
822                  "Unable to insert TargetCandidate in CandidateSet!");
823 
824           // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations
825           // of the FC1 loop will attempt to fuse the new (fused) loop with the
826           // remaining candidates in the current candidate set.
827           FC0 = FC1 = InsertPos.first;
828 
829           LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
830                             << "\n");
831 
832           Fused = true;
833         }
834       }
835     }
836     return Fused;
837   }
838 
839   /// Rewrite all additive recurrences in a SCEV to use a new loop.
840   class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
841   public:
842     AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
843                        bool UseMax = true)
844         : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
845           NewL(NewL) {}
846 
847     const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
848       const Loop *ExprL = Expr->getLoop();
849       SmallVector<const SCEV *, 2> Operands;
850       if (ExprL == &OldL) {
851         Operands.append(Expr->op_begin(), Expr->op_end());
852         return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
853       }
854 
855       if (OldL.contains(ExprL)) {
856         bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
857         if (!UseMax || !Pos || !Expr->isAffine()) {
858           Valid = false;
859           return Expr;
860         }
861         return visit(Expr->getStart());
862       }
863 
864       for (const SCEV *Op : Expr->operands())
865         Operands.push_back(visit(Op));
866       return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
867     }
868 
869     bool wasValidSCEV() const { return Valid; }
870 
871   private:
872     bool Valid, UseMax;
873     const Loop &OldL, &NewL;
874   };
875 
876   /// Return false if the access functions of \p I0 and \p I1 could cause
877   /// a negative dependence.
878   bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
879                             Instruction &I1, bool EqualIsInvalid) {
880     Value *Ptr0 = getLoadStorePointerOperand(&I0);
881     Value *Ptr1 = getLoadStorePointerOperand(&I1);
882     if (!Ptr0 || !Ptr1)
883       return false;
884 
885     const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
886     const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
887 #ifndef NDEBUG
888     if (VerboseFusionDebugging)
889       LLVM_DEBUG(dbgs() << "    Access function check: " << *SCEVPtr0 << " vs "
890                         << *SCEVPtr1 << "\n");
891 #endif
892     AddRecLoopReplacer Rewriter(SE, L0, L1);
893     SCEVPtr0 = Rewriter.visit(SCEVPtr0);
894 #ifndef NDEBUG
895     if (VerboseFusionDebugging)
896       LLVM_DEBUG(dbgs() << "    Access function after rewrite: " << *SCEVPtr0
897                         << " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
898 #endif
899     if (!Rewriter.wasValidSCEV())
900       return false;
901 
902     // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by
903     //       L0) and the other is not. We could check if it is monotone and test
904     //       the beginning and end value instead.
905 
906     BasicBlock *L0Header = L0.getHeader();
907     auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
908       const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
909       if (!AddRec)
910         return false;
911       return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
912              !DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
913     };
914     if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
915       return false;
916 
917     ICmpInst::Predicate Pred =
918         EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
919     bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
920 #ifndef NDEBUG
921     if (VerboseFusionDebugging)
922       LLVM_DEBUG(dbgs() << "    Relation: " << *SCEVPtr0
923                         << (IsAlwaysGE ? "  >=  " : "  may <  ") << *SCEVPtr1
924                         << "\n");
925 #endif
926     return IsAlwaysGE;
927   }
928 
929   /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
930   /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses
931   /// specified by @p DepChoice are used to determine this.
932   bool dependencesAllowFusion(const FusionCandidate &FC0,
933                               const FusionCandidate &FC1, Instruction &I0,
934                               Instruction &I1, bool AnyDep,
935                               FusionDependenceAnalysisChoice DepChoice) {
936 #ifndef NDEBUG
937     if (VerboseFusionDebugging) {
938       LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
939                         << DepChoice << "\n");
940     }
941 #endif
942     switch (DepChoice) {
943     case FUSION_DEPENDENCE_ANALYSIS_SCEV:
944       return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
945     case FUSION_DEPENDENCE_ANALYSIS_DA: {
946       auto DepResult = DI.depends(&I0, &I1, true);
947       if (!DepResult)
948         return true;
949 #ifndef NDEBUG
950       if (VerboseFusionDebugging) {
951         LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
952                    dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
953                           << (DepResult->isOrdered() ? "true" : "false")
954                           << "]\n");
955         LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
956                           << "\n");
957       }
958 #endif
959 
960       if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
961         LLVM_DEBUG(
962             dbgs() << "TODO: Implement pred/succ dependence handling!\n");
963 
964       // TODO: Can we actually use the dependence info analysis here?
965       return false;
966     }
967 
968     case FUSION_DEPENDENCE_ANALYSIS_ALL:
969       return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
970                                     FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
971              dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
972                                     FUSION_DEPENDENCE_ANALYSIS_DA);
973     }
974 
975     llvm_unreachable("Unknown fusion dependence analysis choice!");
976   }
977 
978   /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
979   bool dependencesAllowFusion(const FusionCandidate &FC0,
980                               const FusionCandidate &FC1) {
981     LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
982                       << "\n");
983     assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
984     assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
985 
986     for (Instruction *WriteL0 : FC0.MemWrites) {
987       for (Instruction *WriteL1 : FC1.MemWrites)
988         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
989                                     /* AnyDep */ false,
990                                     FusionDependenceAnalysis)) {
991           InvalidDependencies++;
992           return false;
993         }
994       for (Instruction *ReadL1 : FC1.MemReads)
995         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
996                                     /* AnyDep */ false,
997                                     FusionDependenceAnalysis)) {
998           InvalidDependencies++;
999           return false;
1000         }
1001     }
1002 
1003     for (Instruction *WriteL1 : FC1.MemWrites) {
1004       for (Instruction *WriteL0 : FC0.MemWrites)
1005         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1006                                     /* AnyDep */ false,
1007                                     FusionDependenceAnalysis)) {
1008           InvalidDependencies++;
1009           return false;
1010         }
1011       for (Instruction *ReadL0 : FC0.MemReads)
1012         if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
1013                                     /* AnyDep */ false,
1014                                     FusionDependenceAnalysis)) {
1015           InvalidDependencies++;
1016           return false;
1017         }
1018     }
1019 
1020     // Walk through all uses in FC1. For each use, find the reaching def. If the
1021     // def is located in FC0 then it is is not safe to fuse.
1022     for (BasicBlock *BB : FC1.L->blocks())
1023       for (Instruction &I : *BB)
1024         for (auto &Op : I.operands())
1025           if (Instruction *Def = dyn_cast<Instruction>(Op))
1026             if (FC0.L->contains(Def->getParent())) {
1027               InvalidDependencies++;
1028               return false;
1029             }
1030 
1031     return true;
1032   }
1033 
1034   /// Determine if two fusion candidates are adjacent in the CFG.
1035   ///
1036   /// This method will determine if there are additional basic blocks in the CFG
1037   /// between the exit of \p FC0 and the entry of \p FC1.
1038   /// If the two candidates are guarded loops, then it checks whether the
1039   /// non-loop successor of the \p FC0 guard branch is the entry block of \p
1040   /// FC1. If not, then the loops are not adjacent. If the two candidates are
1041   /// not guarded loops, then it checks whether the exit block of \p FC0 is the
1042   /// preheader of \p FC1.
1043   bool isAdjacent(const FusionCandidate &FC0,
1044                   const FusionCandidate &FC1) const {
1045     // If the successor of the guard branch is FC1, then the loops are adjacent
1046     if (FC0.GuardBranch)
1047       return FC0.getNonLoopBlock() == FC1.getEntryBlock();
1048     else
1049       return FC0.ExitBlock == FC1.getEntryBlock();
1050   }
1051 
1052   /// Determine if two fusion candidates have identical guards
1053   ///
1054   /// This method will determine if two fusion candidates have the same guards.
1055   /// The guards are considered the same if:
1056   ///   1. The instructions to compute the condition used in the compare are
1057   ///      identical.
1058   ///   2. The successors of the guard have the same flow into/around the loop.
1059   /// If the compare instructions are identical, then the first successor of the
1060   /// guard must go to the same place (either the preheader of the loop or the
1061   /// NonLoopBlock). In other words, the the first successor of both loops must
1062   /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
1063   /// the NonLoopBlock). The same must be true for the second successor.
1064   bool haveIdenticalGuards(const FusionCandidate &FC0,
1065                            const FusionCandidate &FC1) const {
1066     assert(FC0.GuardBranch && FC1.GuardBranch &&
1067            "Expecting FC0 and FC1 to be guarded loops.");
1068 
1069     if (auto FC0CmpInst =
1070             dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
1071       if (auto FC1CmpInst =
1072               dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
1073         if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1074           return false;
1075 
1076     // The compare instructions are identical.
1077     // Now make sure the successor of the guards have the same flow into/around
1078     // the loop
1079     if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1080       return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1081     else
1082       return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1083   }
1084 
1085   /// Check that the guard for \p FC *only* contains the cmp/branch for the
1086   /// guard.
1087   /// Once we are able to handle intervening code, any code in the guard block
1088   /// for FC1 will need to be treated as intervening code and checked whether
1089   /// it can safely move around the loops.
1090   bool isEmptyGuardBlock(const FusionCandidate &FC) const {
1091     assert(FC.GuardBranch && "Expecting a fusion candidate with guard branch.");
1092     if (auto *CmpInst = dyn_cast<Instruction>(FC.GuardBranch->getCondition())) {
1093       auto *GuardBlock = FC.GuardBranch->getParent();
1094       // If the generation of the cmp value is in GuardBlock, then the size of
1095       // the guard block should be 2 (cmp + branch). If the generation of the
1096       // cmp value is in a different block, then the size of the guard block
1097       // should only be 1.
1098       if (CmpInst->getParent() == GuardBlock)
1099         return GuardBlock->size() == 2;
1100       else
1101         return GuardBlock->size() == 1;
1102     }
1103 
1104     return false;
1105   }
1106 
1107   bool isEmptyPreheader(const FusionCandidate &FC) const {
1108     assert(FC.Preheader && "Expecting a valid preheader");
1109     return FC.Preheader->size() == 1;
1110   }
1111 
1112   bool isEmptyExitBlock(const FusionCandidate &FC) const {
1113     assert(FC.ExitBlock && "Expecting a valid exit block");
1114     return FC.ExitBlock->size() == 1;
1115   }
1116 
1117   /// Fuse two fusion candidates, creating a new fused loop.
1118   ///
1119   /// This method contains the mechanics of fusing two loops, represented by \p
1120   /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
1121   /// postdominates \p FC0 (making them control flow equivalent). It also
1122   /// assumes that the other conditions for fusion have been met: adjacent,
1123   /// identical trip counts, and no negative distance dependencies exist that
1124   /// would prevent fusion. Thus, there is no checking for these conditions in
1125   /// this method.
1126   ///
1127   /// Fusion is performed by rewiring the CFG to update successor blocks of the
1128   /// components of tho loop. Specifically, the following changes are done:
1129   ///
1130   ///   1. The preheader of \p FC1 is removed as it is no longer necessary
1131   ///   (because it is currently only a single statement block).
1132   ///   2. The latch of \p FC0 is modified to jump to the header of \p FC1.
1133   ///   3. The latch of \p FC1 i modified to jump to the header of \p FC0.
1134   ///   4. All blocks from \p FC1 are removed from FC1 and added to FC0.
1135   ///
1136   /// All of these modifications are done with dominator tree updates, thus
1137   /// keeping the dominator (and post dominator) information up-to-date.
1138   ///
1139   /// This can be improved in the future by actually merging blocks during
1140   /// fusion. For example, the preheader of \p FC1 can be merged with the
1141   /// preheader of \p FC0. This would allow loops with more than a single
1142   /// statement in the preheader to be fused. Similarly, the latch blocks of the
1143   /// two loops could also be fused into a single block. This will require
1144   /// analysis to prove it is safe to move the contents of the block past
1145   /// existing code, which currently has not been implemented.
1146   Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1147     assert(FC0.isValid() && FC1.isValid() &&
1148            "Expecting valid fusion candidates");
1149 
1150     LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
1151                dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
1152 
1153     // Fusing guarded loops is handled slightly differently than non-guarded
1154     // loops and has been broken out into a separate method instead of trying to
1155     // intersperse the logic within a single method.
1156     if (FC0.GuardBranch)
1157       return fuseGuardedLoops(FC0, FC1);
1158 
1159     assert(FC1.Preheader == FC0.ExitBlock);
1160     assert(FC1.Preheader->size() == 1 &&
1161            FC1.Preheader->getSingleSuccessor() == FC1.Header);
1162 
1163     // Remember the phi nodes originally in the header of FC0 in order to rewire
1164     // them later. However, this is only necessary if the new loop carried
1165     // values might not dominate the exiting branch. While we do not generally
1166     // test if this is the case but simply insert intermediate phi nodes, we
1167     // need to make sure these intermediate phi nodes have different
1168     // predecessors. To this end, we filter the special case where the exiting
1169     // block is the latch block of the first loop. Nothing needs to be done
1170     // anyway as all loop carried values dominate the latch and thereby also the
1171     // exiting branch.
1172     SmallVector<PHINode *, 8> OriginalFC0PHIs;
1173     if (FC0.ExitingBlock != FC0.Latch)
1174       for (PHINode &PHI : FC0.Header->phis())
1175         OriginalFC0PHIs.push_back(&PHI);
1176 
1177     // Replace incoming blocks for header PHIs first.
1178     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1179     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1180 
1181     // Then modify the control flow and update DT and PDT.
1182     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
1183 
1184     // The old exiting block of the first loop (FC0) has to jump to the header
1185     // of the second as we need to execute the code in the second header block
1186     // regardless of the trip count. That is, if the trip count is 0, so the
1187     // back edge is never taken, we still have to execute both loop headers,
1188     // especially (but not only!) if the second is a do-while style loop.
1189     // However, doing so might invalidate the phi nodes of the first loop as
1190     // the new values do only need to dominate their latch and not the exiting
1191     // predicate. To remedy this potential problem we always introduce phi
1192     // nodes in the header of the second loop later that select the loop carried
1193     // value, if the second header was reached through an old latch of the
1194     // first, or undef otherwise. This is sound as exiting the first implies the
1195     // second will exit too, __without__ taking the back-edge. [Their
1196     // trip-counts are equal after all.
1197     // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go
1198     // to FC1.Header? I think this is basically what the three sequences are
1199     // trying to accomplish; however, doing this directly in the CFG may mean
1200     // the DT/PDT becomes invalid
1201     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1202                                                          FC1.Header);
1203     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1204         DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1205     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1206         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1207 
1208     // The pre-header of L1 is not necessary anymore.
1209     assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader));
1210     FC1.Preheader->getTerminator()->eraseFromParent();
1211     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1212     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1213         DominatorTree::Delete, FC1.Preheader, FC1.Header));
1214 
1215     // Moves the phi nodes from the second to the first loops header block.
1216     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1217       if (SE.isSCEVable(PHI->getType()))
1218         SE.forgetValue(PHI);
1219       if (PHI->hasNUsesOrMore(1))
1220         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1221       else
1222         PHI->eraseFromParent();
1223     }
1224 
1225     // Introduce new phi nodes in the second loop header to ensure
1226     // exiting the first and jumping to the header of the second does not break
1227     // the SSA property of the phis originally in the first loop. See also the
1228     // comment above.
1229     Instruction *L1HeaderIP = &FC1.Header->front();
1230     for (PHINode *LCPHI : OriginalFC0PHIs) {
1231       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1232       assert(L1LatchBBIdx >= 0 &&
1233              "Expected loop carried value to be rewired at this point!");
1234 
1235       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1236 
1237       PHINode *L1HeaderPHI = PHINode::Create(
1238           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
1239       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1240       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
1241                                FC0.ExitingBlock);
1242 
1243       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1244     }
1245 
1246     // Replace latch terminator destinations.
1247     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1248     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1249 
1250     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1251     // performed the updates above.
1252     if (FC0.Latch != FC0.ExitingBlock)
1253       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1254           DominatorTree::Insert, FC0.Latch, FC1.Header));
1255 
1256     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1257                                                        FC0.Latch, FC0.Header));
1258     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1259                                                        FC1.Latch, FC0.Header));
1260     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1261                                                        FC1.Latch, FC1.Header));
1262 
1263     // Update DT/PDT
1264     DTU.applyUpdates(TreeUpdates);
1265 
1266     LI.removeBlock(FC1.Preheader);
1267     DTU.deleteBB(FC1.Preheader);
1268     DTU.flush();
1269 
1270     // Is there a way to keep SE up-to-date so we don't need to forget the loops
1271     // and rebuild the information in subsequent passes of fusion?
1272     SE.forgetLoop(FC1.L);
1273     SE.forgetLoop(FC0.L);
1274 
1275     // Merge the loops.
1276     SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(),
1277                                         FC1.L->block_end());
1278     for (BasicBlock *BB : Blocks) {
1279       FC0.L->addBlockEntry(BB);
1280       FC1.L->removeBlockFromLoop(BB);
1281       if (LI.getLoopFor(BB) != FC1.L)
1282         continue;
1283       LI.changeLoopFor(BB, FC0.L);
1284     }
1285     while (!FC1.L->empty()) {
1286       const auto &ChildLoopIt = FC1.L->begin();
1287       Loop *ChildLoop = *ChildLoopIt;
1288       FC1.L->removeChildLoop(ChildLoopIt);
1289       FC0.L->addChildLoop(ChildLoop);
1290     }
1291 
1292     // Delete the now empty loop L1.
1293     LI.erase(FC1.L);
1294 
1295 #ifndef NDEBUG
1296     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1297     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1298     assert(PDT.verify());
1299     LI.verify(DT);
1300     SE.verify();
1301 #endif
1302 
1303     LLVM_DEBUG(dbgs() << "Fusion done:\n");
1304 
1305     return FC0.L;
1306   }
1307 
1308   /// Report details on loop fusion opportunities.
1309   ///
1310   /// This template function can be used to report both successful and missed
1311   /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
1312   /// be one of:
1313   ///   - OptimizationRemarkMissed to report when loop fusion is unsuccessful
1314   ///     given two valid fusion candidates.
1315   ///   - OptimizationRemark to report successful fusion of two fusion
1316   ///     candidates.
1317   /// The remarks will be printed using the form:
1318   ///    <path/filename>:<line number>:<column number>: [<function name>]:
1319   ///       <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
1320   template <typename RemarkKind>
1321   void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
1322                         llvm::Statistic &Stat) {
1323     assert(FC0.Preheader && FC1.Preheader &&
1324            "Expecting valid fusion candidates");
1325     using namespace ore;
1326     ++Stat;
1327     ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
1328                         FC0.Preheader)
1329              << "[" << FC0.Preheader->getParent()->getName()
1330              << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
1331              << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
1332              << ": " << Stat.getDesc());
1333   }
1334 
1335   /// Fuse two guarded fusion candidates, creating a new fused loop.
1336   ///
1337   /// Fusing guarded loops is handled much the same way as fusing non-guarded
1338   /// loops. The rewiring of the CFG is slightly different though, because of
1339   /// the presence of the guards around the loops and the exit blocks after the
1340   /// loop body. As such, the new loop is rewired as follows:
1341   ///    1. Keep the guard branch from FC0 and use the non-loop block target
1342   /// from the FC1 guard branch.
1343   ///    2. Remove the exit block from FC0 (this exit block should be empty
1344   /// right now).
1345   ///    3. Remove the guard branch for FC1
1346   ///    4. Remove the preheader for FC1.
1347   /// The exit block successor for the latch of FC0 is updated to be the header
1348   /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
1349   /// be the header of FC0, thus creating the fused loop.
1350   Loop *fuseGuardedLoops(const FusionCandidate &FC0,
1351                          const FusionCandidate &FC1) {
1352     assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
1353 
1354     BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1355     BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1356     BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1357     BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1358 
1359     assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
1360 
1361     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
1362 
1363     ////////////////////////////////////////////////////////////////////////////
1364     // Update the Loop Guard
1365     ////////////////////////////////////////////////////////////////////////////
1366     // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
1367     // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
1368     // Thus, one path from the guard goes to the preheader for FC0 (and thus
1369     // executes the new fused loop) and the other path goes to the NonLoopBlock
1370     // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1371     FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1372     FC0.ExitBlock->getTerminator()->replaceUsesOfWith(FC1GuardBlock,
1373                                                       FC1.Header);
1374 
1375     // The guard of FC1 is not necessary anymore.
1376     FC1.GuardBranch->eraseFromParent();
1377     new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
1378 
1379     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1380         DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1381     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1382         DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1383     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1384         DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1385     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1386         DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1387 
1388     assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) &&
1389            "Expecting guard block to have no predecessors");
1390     assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) &&
1391            "Expecting guard block to have no successors");
1392 
1393     // Remember the phi nodes originally in the header of FC0 in order to rewire
1394     // them later. However, this is only necessary if the new loop carried
1395     // values might not dominate the exiting branch. While we do not generally
1396     // test if this is the case but simply insert intermediate phi nodes, we
1397     // need to make sure these intermediate phi nodes have different
1398     // predecessors. To this end, we filter the special case where the exiting
1399     // block is the latch block of the first loop. Nothing needs to be done
1400     // anyway as all loop carried values dominate the latch and thereby also the
1401     // exiting branch.
1402     // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
1403     // (because the loops are rotated. Thus, nothing will ever be added to
1404     // OriginalFC0PHIs.
1405     SmallVector<PHINode *, 8> OriginalFC0PHIs;
1406     if (FC0.ExitingBlock != FC0.Latch)
1407       for (PHINode &PHI : FC0.Header->phis())
1408         OriginalFC0PHIs.push_back(&PHI);
1409 
1410     assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
1411 
1412     // Replace incoming blocks for header PHIs first.
1413     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1414     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1415 
1416     // The old exiting block of the first loop (FC0) has to jump to the header
1417     // of the second as we need to execute the code in the second header block
1418     // regardless of the trip count. That is, if the trip count is 0, so the
1419     // back edge is never taken, we still have to execute both loop headers,
1420     // especially (but not only!) if the second is a do-while style loop.
1421     // However, doing so might invalidate the phi nodes of the first loop as
1422     // the new values do only need to dominate their latch and not the exiting
1423     // predicate. To remedy this potential problem we always introduce phi
1424     // nodes in the header of the second loop later that select the loop carried
1425     // value, if the second header was reached through an old latch of the
1426     // first, or undef otherwise. This is sound as exiting the first implies the
1427     // second will exit too, __without__ taking the back-edge (their
1428     // trip-counts are equal after all).
1429     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1430                                                          FC1.Header);
1431 
1432     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1433         DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1434     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1435         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1436 
1437     // Remove FC0 Exit Block
1438     // The exit block for FC0 is no longer needed since control will flow
1439     // directly to the header of FC1. Since it is an empty block, it can be
1440     // removed at this point.
1441     // TODO: In the future, we can handle non-empty exit blocks my merging any
1442     // instructions from FC0 exit block into FC1 exit block prior to removing
1443     // the block.
1444     assert(pred_begin(FC0.ExitBlock) == pred_end(FC0.ExitBlock) &&
1445            "Expecting exit block to be empty");
1446     FC0.ExitBlock->getTerminator()->eraseFromParent();
1447     new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1448 
1449     // Remove FC1 Preheader
1450     // The pre-header of L1 is not necessary anymore.
1451     assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader));
1452     FC1.Preheader->getTerminator()->eraseFromParent();
1453     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1454     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1455         DominatorTree::Delete, FC1.Preheader, FC1.Header));
1456 
1457     // Moves the phi nodes from the second to the first loops header block.
1458     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1459       if (SE.isSCEVable(PHI->getType()))
1460         SE.forgetValue(PHI);
1461       if (PHI->hasNUsesOrMore(1))
1462         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1463       else
1464         PHI->eraseFromParent();
1465     }
1466 
1467     // Introduce new phi nodes in the second loop header to ensure
1468     // exiting the first and jumping to the header of the second does not break
1469     // the SSA property of the phis originally in the first loop. See also the
1470     // comment above.
1471     Instruction *L1HeaderIP = &FC1.Header->front();
1472     for (PHINode *LCPHI : OriginalFC0PHIs) {
1473       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1474       assert(L1LatchBBIdx >= 0 &&
1475              "Expected loop carried value to be rewired at this point!");
1476 
1477       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1478 
1479       PHINode *L1HeaderPHI = PHINode::Create(
1480           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
1481       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1482       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
1483                                FC0.ExitingBlock);
1484 
1485       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1486     }
1487 
1488     // Update the latches
1489 
1490     // Replace latch terminator destinations.
1491     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1492     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1493 
1494     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1495     // performed the updates above.
1496     if (FC0.Latch != FC0.ExitingBlock)
1497       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1498           DominatorTree::Insert, FC0.Latch, FC1.Header));
1499 
1500     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1501                                                        FC0.Latch, FC0.Header));
1502     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1503                                                        FC1.Latch, FC0.Header));
1504     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1505                                                        FC1.Latch, FC1.Header));
1506 
1507     // All done
1508     // Apply the updates to the Dominator Tree and cleanup.
1509 
1510     assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) &&
1511            "FC1GuardBlock has successors!!");
1512     assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) &&
1513            "FC1GuardBlock has predecessors!!");
1514 
1515     // Update DT/PDT
1516     DTU.applyUpdates(TreeUpdates);
1517 
1518     LI.removeBlock(FC1.Preheader);
1519     DTU.deleteBB(FC1.Preheader);
1520     DTU.deleteBB(FC0.ExitBlock);
1521     DTU.flush();
1522 
1523     // Is there a way to keep SE up-to-date so we don't need to forget the loops
1524     // and rebuild the information in subsequent passes of fusion?
1525     SE.forgetLoop(FC1.L);
1526     SE.forgetLoop(FC0.L);
1527 
1528     // Merge the loops.
1529     SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(),
1530                                         FC1.L->block_end());
1531     for (BasicBlock *BB : Blocks) {
1532       FC0.L->addBlockEntry(BB);
1533       FC1.L->removeBlockFromLoop(BB);
1534       if (LI.getLoopFor(BB) != FC1.L)
1535         continue;
1536       LI.changeLoopFor(BB, FC0.L);
1537     }
1538     while (!FC1.L->empty()) {
1539       const auto &ChildLoopIt = FC1.L->begin();
1540       Loop *ChildLoop = *ChildLoopIt;
1541       FC1.L->removeChildLoop(ChildLoopIt);
1542       FC0.L->addChildLoop(ChildLoop);
1543     }
1544 
1545     // Delete the now empty loop L1.
1546     LI.erase(FC1.L);
1547 
1548 #ifndef NDEBUG
1549     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1550     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1551     assert(PDT.verify());
1552     LI.verify(DT);
1553     SE.verify();
1554 #endif
1555 
1556     LLVM_DEBUG(dbgs() << "Fusion done:\n");
1557 
1558     return FC0.L;
1559   }
1560 };
1561 
1562 struct LoopFuseLegacy : public FunctionPass {
1563 
1564   static char ID;
1565 
1566   LoopFuseLegacy() : FunctionPass(ID) {
1567     initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
1568   }
1569 
1570   void getAnalysisUsage(AnalysisUsage &AU) const override {
1571     AU.addRequiredID(LoopSimplifyID);
1572     AU.addRequired<ScalarEvolutionWrapperPass>();
1573     AU.addRequired<LoopInfoWrapperPass>();
1574     AU.addRequired<DominatorTreeWrapperPass>();
1575     AU.addRequired<PostDominatorTreeWrapperPass>();
1576     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1577     AU.addRequired<DependenceAnalysisWrapperPass>();
1578 
1579     AU.addPreserved<ScalarEvolutionWrapperPass>();
1580     AU.addPreserved<LoopInfoWrapperPass>();
1581     AU.addPreserved<DominatorTreeWrapperPass>();
1582     AU.addPreserved<PostDominatorTreeWrapperPass>();
1583   }
1584 
1585   bool runOnFunction(Function &F) override {
1586     if (skipFunction(F))
1587       return false;
1588     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1589     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1590     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1591     auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1592     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1593     auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1594 
1595     const DataLayout &DL = F.getParent()->getDataLayout();
1596     LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1597     return LF.fuseLoops(F);
1598   }
1599 };
1600 } // namespace
1601 
1602 PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
1603   auto &LI = AM.getResult<LoopAnalysis>(F);
1604   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1605   auto &DI = AM.getResult<DependenceAnalysis>(F);
1606   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1607   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1608   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1609 
1610   const DataLayout &DL = F.getParent()->getDataLayout();
1611   LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1612   bool Changed = LF.fuseLoops(F);
1613   if (!Changed)
1614     return PreservedAnalyses::all();
1615 
1616   PreservedAnalyses PA;
1617   PA.preserve<DominatorTreeAnalysis>();
1618   PA.preserve<PostDominatorTreeAnalysis>();
1619   PA.preserve<ScalarEvolutionAnalysis>();
1620   PA.preserve<LoopAnalysis>();
1621   return PA;
1622 }
1623 
1624 char LoopFuseLegacy::ID = 0;
1625 
1626 INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
1627                       false)
1628 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1629 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1630 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1631 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1632 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1633 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1634 INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
1635 
1636 FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }
1637