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