LLVM 24.0.0git
LoopFuse.cpp
Go to the documentation of this file.
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
48#include "llvm/ADT/Statistic.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Verifier.h"
60#include "llvm/Support/Debug.h"
66#include <list>
67
68using namespace llvm;
69
70#define DEBUG_TYPE "loop-fusion"
71
72STATISTIC(FuseCounter, "Loops fused");
73STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
74STATISTIC(InvalidLoopStructure, "Loop has invalid structure");
75STATISTIC(AddressTakenBB, "Basic block has address taken");
76STATISTIC(MayThrowException, "Loop may throw an exception");
77STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
78STATISTIC(ContainsAtomicAccess, "Loop contains an atomic access");
79STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
80STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
81STATISTIC(UnknownTripCount, "Loop has unknown trip count");
82STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
83STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
85 NonEmptyPreheader,
86 "Loop has a non-empty preheader with instructions that cannot be moved");
87STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
88STATISTIC(NonIdenticalGuards, "Candidates have different guards");
89STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
90 "instructions that cannot be moved");
91STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
92 "instructions that cannot be moved");
93STATISTIC(NotRotated, "Candidate is not rotated");
94STATISTIC(OnlySecondCandidateIsGuarded,
95 "The second candidate is guarded while the first one is not");
96STATISTIC(NumHoistedInsts, "Number of hoisted preheader instructions.");
97STATISTIC(NumSunkInsts, "Number of sunk preheader instructions.");
98STATISTIC(NumDA, "DA checks passed");
99
101 "loop-fusion-peel-max-count", cl::init(0), cl::Hidden,
102 cl::desc("Max number of iterations to be peeled from a loop, such that "
103 "fusion can take place"));
104
105#ifndef NDEBUG
106static cl::opt<bool>
107 VerboseFusionDebugging("loop-fusion-verbose-debug",
108 cl::desc("Enable verbose debugging for Loop Fusion"),
109 cl::Hidden, cl::init(false));
110#endif
111
112namespace {
113/// This class is used to represent a candidate for loop fusion. When it is
114/// constructed, it checks the conditions for loop fusion to ensure that it
115/// represents a valid candidate. It caches several parts of a loop that are
116/// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
117/// of continually querying the underlying Loop to retrieve these values. It is
118/// assumed these will not change throughout loop fusion.
119///
120/// The invalidate method should be used to indicate that the FusionCandidate is
121/// no longer a valid candidate for fusion. Similarly, the isValid() method can
122/// be used to ensure that the FusionCandidate is still valid for fusion.
123struct FusionCandidate {
124 /// Cache of parts of the loop used throughout loop fusion. These should not
125 /// need to change throughout the analysis and transformation.
126 /// These parts are cached to avoid repeatedly looking up in the Loop class.
127
128 /// Preheader of the loop this candidate represents
129 BasicBlock *Preheader;
130 /// Header of the loop this candidate represents
131 BasicBlock *Header;
132 /// Blocks in the loop that exit the loop
133 BasicBlock *ExitingBlock;
134 /// The successor block of this loop (where the exiting blocks go to)
135 BasicBlock *ExitBlock;
136 /// Latch of the loop
137 BasicBlock *Latch;
138 /// The loop that this fusion candidate represents
139 Loop *L;
140 /// Vector of instructions in this loop that read from memory
142 /// Vector of instructions in this loop that write to memory
144 /// Are all of the members of this fusion candidate still valid
145 bool Valid;
146 /// Guard branch of the loop, if it exists
147 CondBrInst *GuardBranch;
148 /// Peeling Paramaters of the Loop.
150 /// Can you Peel this Loop?
151 bool AbleToPeel;
152 /// Has this loop been Peeled
153 bool Peeled;
154
155 DominatorTree &DT;
156 const PostDominatorTree *PDT;
157
159
160 FusionCandidate(Loop *L, DominatorTree &DT, const PostDominatorTree *PDT,
162 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
163 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
164 Latch(L->getLoopLatch()), L(L), Valid(true),
165 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
166 Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
167
168 // Walk over all blocks in the loop and check for conditions that may
169 // prevent fusion. For each block, walk over all instructions and collect
170 // the memory reads and writes If any instructions that prevent fusion are
171 // found, invalidate this object and return.
172 for (BasicBlock *BB : L->blocks()) {
173 if (BB->hasAddressTaken()) {
174 invalidate();
175 ++AddressTakenBB;
176 reportInvalidCandidate("AddressTakenBB",
177 "Basic block has address taken");
178 return;
179 }
180
181 for (Instruction &I : *BB) {
182 if (I.mayThrow()) {
183 invalidate();
184 ++MayThrowException;
185 reportInvalidCandidate("MayThrowException",
186 "Loop may throw an exception");
187 return;
188 }
189 if (I.isVolatile()) {
190 invalidate();
191 ++ContainsVolatileAccess;
192 reportInvalidCandidate("ContainsVolatileAccess",
193 "Loop contains a volatile access");
194 return;
195 }
196 // Atomic accesses impose ordering/synchronization constraints that the
197 // dependence analysis used for fusion does not model, so reordering
198 // them across the fused body could be unsafe.
199 if (I.isAtomic()) {
200 invalidate();
201 ++ContainsAtomicAccess;
202 reportInvalidCandidate("ContainsAtomicAccess",
203 "Loop contains an atomic access");
204 return;
205 }
206 if (I.mayWriteToMemory())
207 MemWrites.push_back(&I);
208 if (I.mayReadFromMemory())
209 MemReads.push_back(&I);
210 }
211 }
212 }
213
214 /// Check if all members of the class are valid.
215 bool isValid() const {
216 return Preheader && ExitingBlock && ExitBlock && Latch && L &&
217 !L->isInvalid() && Valid;
218 }
219
220 /// Verify that all members are in sync with the Loop object.
221 void verify() const {
222 assert(isValid() && "Candidate is not valid!!");
223 assert(!L->isInvalid() && "Loop is invalid!");
224 assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
225 assert(Header == L->getHeader() && "Header is out of sync");
226 assert(ExitingBlock == L->getExitingBlock() &&
227 "Exiting Blocks is out of sync");
228 assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
229 assert(Latch == L->getLoopLatch() && "Latch is out of sync");
230 }
231
232 /// Get the entry block for this fusion candidate.
233 ///
234 /// If this fusion candidate represents a guarded loop, the entry block is the
235 /// loop guard block. If it represents an unguarded loop, the entry block is
236 /// the preheader of the loop.
237 BasicBlock *getEntryBlock() const {
238 if (GuardBranch)
239 return GuardBranch->getParent();
240 return Preheader;
241 }
242
243 /// After Peeling the loop is modified quite a bit, hence all of the Blocks
244 /// need to be updated accordingly.
245 void updateAfterPeeling() {
246 Preheader = L->getLoopPreheader();
247 Header = L->getHeader();
248 ExitingBlock = L->getExitingBlock();
249 ExitBlock = L->getExitBlock();
250 Latch = L->getLoopLatch();
251 verify();
252 }
253
254 /// Given a guarded loop, get the successor of the guard that is not in the
255 /// loop.
256 ///
257 /// This method returns the successor of the loop guard that is not located
258 /// within the loop (i.e., the successor of the guard that is not the
259 /// preheader).
260 /// This method is only valid for guarded loops.
261 BasicBlock *getNonLoopBlock() const {
262 assert(GuardBranch && "Only valid on guarded loops.");
263 if (Peeled)
264 return GuardBranch->getSuccessor(1);
265 return (GuardBranch->getSuccessor(0) == Preheader)
266 ? GuardBranch->getSuccessor(1)
267 : GuardBranch->getSuccessor(0);
268 }
269
270#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
271 LLVM_DUMP_METHOD void dump() const {
272 dbgs() << "\tGuardBranch: ";
273 if (GuardBranch)
274 dbgs() << *GuardBranch;
275 else
276 dbgs() << "nullptr";
277 dbgs() << "\n"
278 << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
279 << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
280 << "\n"
281 << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
282 << "\tExitingBB: "
283 << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
284 << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
285 << "\n"
286 << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
287 << "\tEntryBlock: "
288 << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
289 << "\n";
290 }
291#endif
292
293 /// Determine if a fusion candidate (representing a loop) is eligible for
294 /// fusion. Note that this only checks whether a single loop can be fused - it
295 /// does not check whether it is *legal* to fuse two loops together.
296 bool isEligibleForFusion(ScalarEvolution &SE) const {
297 if (!isValid()) {
298 LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
299 assert(Header && "Header should be guaranteed to exist!");
300 ++InvalidLoopStructure;
301 return false;
302 }
303
304 // Require ScalarEvolution to be able to determine a trip count.
306 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
307 << " trip count not computable!\n");
308 ++UnknownTripCount;
309 return reportInvalidCandidate("UnknownTripCount",
310 "Loop has unknown trip count");
311 }
312
313 if (!L->isLoopSimplifyForm()) {
314 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
315 << " is not in simplified form!\n");
316 ++NotSimplifiedForm;
317 return reportInvalidCandidate("NotSimplifiedForm",
318 "Loop is not in simplified form");
319 }
320
321 if (!L->isRotatedForm()) {
322 LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
323 ++NotRotated;
324 return reportInvalidCandidate("NotRotated", "Candidate is not rotated");
325 }
326
327 return true;
328 }
329
330private:
331 // This is only used internally for now, to clear the MemWrites and MemReads
332 // list and setting Valid to false. I can't envision other uses of this right
333 // now, since once FusionCandidates are put into the FusionCandidateList they
334 // are immutable. Thus, any time we need to change/update a FusionCandidate,
335 // we must create a new one and insert it into the FusionCandidateList to
336 // ensure the FusionCandidateList remains ordered correctly.
337 void invalidate() {
338 MemWrites.clear();
339 MemReads.clear();
340 Valid = false;
341 }
342
343 // Emit an analysis remark explaining why this loop cannot be fused. The
344 // remark is built from explicit strings so it does not depend on whether
345 // statistics are enabled. \p RemarkName is the -Rpass remark identifier and
346 // \p RemarkMsg the human-readable reason.
347 bool reportInvalidCandidate(StringRef RemarkName, StringRef RemarkMsg) const {
348 using namespace ore;
349 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "InvalidCandidate",
350 L->getStartLoc(), L->getHeader())
351 << "Loop is not a candidate for fusion");
352
354 L->getStartLoc(), L->getHeader())
355 << "[" << L->getHeader()->getParent()->getName() << "]: "
356 << "Loop is not a candidate for fusion: " << RemarkMsg);
357 return false;
358 }
359};
360} // namespace
361
363
364// List of adjacent fusion candidates in order. Thus, if FC0 comes *before* FC1
365// in a FusionCandidateList, then FC0 dominates FC1, FC1 post-dominates FC0,
366// and they are adjacent.
367using FusionCandidateList = std::list<FusionCandidate>;
369
370#ifndef NDEBUG
371static void printLoopVector(const LoopVector &LV) {
372 dbgs() << "****************************\n";
373 for (const Loop *L : LV)
374 printLoop(*L, dbgs());
375 dbgs() << "****************************\n";
376}
377
378static raw_ostream &operator<<(raw_ostream &OS, const FusionCandidate &FC) {
379 if (FC.isValid())
380 OS << FC.Preheader->getName();
381 else
382 OS << "<Invalid>";
383
384 return OS;
385}
386
388 const FusionCandidateList &CandList) {
389 for (const FusionCandidate &FC : CandList)
390 OS << FC << '\n';
391
392 return OS;
393}
394
395static void
397 dbgs() << "Fusion Candidates: \n";
398 for (const auto &CandidateList : FusionCandidates) {
399 dbgs() << "*** Fusion Candidate List ***\n";
400 dbgs() << CandidateList;
401 dbgs() << "****************************\n";
402 }
403}
404#endif // NDEBUG
405
406namespace {
407
408/// Collect all loops in function at the same nest level, starting at the
409/// outermost level.
410///
411/// This data structure collects all loops at the same nest level for a
412/// given function (specified by the LoopInfo object). It starts at the
413/// outermost level.
414struct LoopDepthTree {
415 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
416 using iterator = LoopsOnLevelTy::iterator;
417 using const_iterator = LoopsOnLevelTy::const_iterator;
418
419 LoopDepthTree(LoopInfo &LI) : Depth(1) {
420 if (!LI.empty())
421 LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
422 }
423
424 /// Test whether a given loop has been removed from the function, and thus is
425 /// no longer valid.
426 bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
427
428 /// Record that a given loop has been removed from the function and is no
429 /// longer valid.
430 void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
431
432 /// Descend the tree to the next (inner) nesting level
433 void descend() {
434 LoopsOnLevelTy LoopsOnNextLevel;
435
436 for (const LoopVector &LV : *this)
437 for (Loop *L : LV)
438 if (!isRemovedLoop(L) && L->begin() != L->end())
439 LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
440
441 LoopsOnLevel = LoopsOnNextLevel;
442 RemovedLoops.clear();
443 Depth++;
444 }
445
446 bool empty() const { return size() == 0; }
447 size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
448 unsigned getDepth() const { return Depth; }
449
450 iterator begin() { return LoopsOnLevel.begin(); }
451 iterator end() { return LoopsOnLevel.end(); }
452 const_iterator begin() const { return LoopsOnLevel.begin(); }
453 const_iterator end() const { return LoopsOnLevel.end(); }
454
455private:
456 /// Set of loops that have been removed from the function and are no longer
457 /// valid.
458 SmallPtrSet<const Loop *, 8> RemovedLoops;
459
460 /// Depth of the current level, starting at 1 (outermost loops).
461 unsigned Depth;
462
463 /// Vector of loops at the current depth level that have the same parent loop
464 LoopsOnLevelTy LoopsOnLevel;
465};
466
467struct LoopFuser {
468private:
469 // Sets of control flow equivalent fusion candidates for a given nest level.
470 FusionCandidateCollection FusionCandidates;
471
472 LoopDepthTree LDT;
473 DomTreeUpdater DTU;
474
475 LoopInfo &LI;
476 DominatorTree &DT;
477 DependenceInfo &DI;
478 ScalarEvolution &SE;
479 PostDominatorTree &PDT;
480 OptimizationRemarkEmitter &ORE;
481 AssumptionCache &AC;
482 const TargetTransformInfo &TTI;
483
484public:
485 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
486 ScalarEvolution &SE, PostDominatorTree &PDT,
487 OptimizationRemarkEmitter &ORE, AssumptionCache &AC,
488 const TargetTransformInfo &TTI)
489 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
490 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
491
492 /// This is the main entry point for loop fusion. It will traverse the
493 /// specified function and collect candidate loops to fuse, starting at the
494 /// outermost nesting level and working inwards.
495 bool fuseLoops(Function &F) {
496#ifndef NDEBUG
498 LI.print(dbgs());
499 }
500#endif
501
502 LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
503 << "\n");
504 bool Changed = false;
505
506 while (!LDT.empty()) {
507 LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
508 << LDT.getDepth() << "\n";);
509
510 for (const LoopVector &LV : LDT) {
511 assert(LV.size() > 0 && "Empty loop set was build!");
512
513 // Skip singleton loop sets as they do not offer fusion opportunities on
514 // this level.
515 if (LV.size() == 1)
516 continue;
517#ifndef NDEBUG
519 LLVM_DEBUG({
520 dbgs() << " Visit loop set (#" << LV.size() << "):\n";
521 printLoopVector(LV);
522 });
523 }
524#endif
525
526 collectFusionCandidates(LV);
527 Changed |= fuseCandidates();
528 // All loops in the candidate sets have a common parent (or no parent).
529 // Next loop vector will correspond to a different parent. It is safe
530 // to remove all the candidates currently in the set.
531 FusionCandidates.clear();
532 }
533
534 // Finished analyzing candidates at this level. Descend to the next level.
535 LLVM_DEBUG(dbgs() << "Descend one level!\n");
536 LDT.descend();
537 }
538
539 if (Changed)
540 LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
541
542#ifndef NDEBUG
543 assert(DT.verify());
544 assert(PDT.verify());
545 LI.verify();
546 SE.verify();
547#endif
548
549 LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
550 return Changed;
551 }
552
553private:
554 /// Iterate over all loops in the given loop set and identify the loops that
555 /// are eligible for fusion. Place all eligible fusion candidates into Control
556 /// Flow Equivalent sets, sorted by dominance.
557 void collectFusionCandidates(const LoopVector &LV) {
558 for (Loop *L : LV) {
560 gatherPeelingPreferences(L, SE, TTI, std::nullopt, std::nullopt);
561 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
562 if (!CurrCand.isEligibleForFusion(SE))
563 continue;
564
565 // Go through each list in FusionCandidates and determine if the first or
566 // last loop in the list is strictly adjacent to L. If it is, append L.
567 // If not, go to the next list.
568 // If no suitable list is found, start another list and add it to
569 // FusionCandidates.
570 bool FoundAdjacent = false;
571 for (auto &CurrCandList : FusionCandidates) {
572 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
573 CurrCandList.push_back(CurrCand);
574 FoundAdjacent = true;
575 NumFusionCandidates++;
576#ifndef NDEBUG
578 LLVM_DEBUG(dbgs() << "Adding " << CurrCand
579 << " to existing candidate list\n");
580#endif
581 break;
582 }
583 }
584 if (!FoundAdjacent) {
585 // No list was found. Create a new list and add to FusionCandidates
586#ifndef NDEBUG
588 LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new list\n");
589#endif
590 FusionCandidateList NewCandList;
591 NewCandList.push_back(CurrCand);
592 FusionCandidates.push_back(NewCandList);
593 }
594 }
595 }
596
597 /// Determine if it is beneficial to fuse two loops.
598 ///
599 /// For now, this method simply returns true because we want to fuse as much
600 /// as possible (primarily to test the pass). This method will evolve, over
601 /// time, to add heuristics for profitability of fusion.
602 bool isBeneficialFusion(const FusionCandidate &FC0,
603 const FusionCandidate &FC1) {
604 return true;
605 }
606
607 /// Computes the integer difference in trip counts:
608 /// TripCount(FC0) - TripCount(FC1).
609 ///
610 /// \returns The integer difference, or std::nullopt if it
611 /// cannot be determined.
612 std::optional<int64_t>
613 calculateTripCountDiff(const FusionCandidate &FC0,
614 const FusionCandidate &FC1) const {
615 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
616 if (isa<SCEVCouldNotCompute>(TripCount0)) {
617 UncomputableTripCount++;
618 LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
619 return std::nullopt;
620 }
621
622 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
623 if (isa<SCEVCouldNotCompute>(TripCount1)) {
624 UncomputableTripCount++;
625 LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
626 return std::nullopt;
627 }
628
629 LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
630 << *TripCount1 << " are "
631 << (TripCount0 == TripCount1 ? "identical" : "different")
632 << "\n");
633
634 if (TripCount0 == TripCount1)
635 return 0;
636
637 LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
638 "determining the difference between trip counts\n");
639
640 // Currently only considering loops with a single exit point
641 // and a non-constant trip count. Note that the return value
642 // of getSmallConstantTripCount is a 32 bit number, based on
643 // the existing implementation.
644 const int64_t TC0 =
645 static_cast<int64_t>(SE.getSmallConstantTripCount(FC0.L));
646 const int64_t TC1 =
647 static_cast<int64_t>(SE.getSmallConstantTripCount(FC1.L));
648
649 // If any of the tripcounts are zero that means that loop(s) do not have
650 // a single exit or a constant tripcount.
651 if (TC0 == 0 || TC1 == 0) {
652 LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
653 "have a constant number of iterations. Peeling "
654 "is not benefical\n");
655 return std::nullopt;
656 }
657
658 return TC0 - TC1;
659 }
660
661 void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
662 unsigned PeelCount) {
663 assert(FC0.AbleToPeel && "Should be able to peel loop");
664
665 LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
666 << " iterations of the first loop. \n");
667
669 // LoopFusion is a function pass that neither requires nor preserves
670 // LCSSA, so peelLoop need not preserve it across its internal
671 // simplifyLoop call.
672 peelLoop(FC0.L, PeelCount, /*PeelLast=*/false, &LI, &SE, DT, &AC,
673 /*PreserveLCSSA=*/false, VMap);
674 FC0.Peeled = true;
675 LLVM_DEBUG(dbgs() << "Done Peeling\n");
676
677#ifndef NDEBUG
678 auto TCDiff = calculateTripCountDiff(FC0, FC1);
679
680 assert(TCDiff && *TCDiff == 0 &&
681 "Loops should have identical trip counts after peeling");
682#endif
683
684 FC0.PP.PeelCount += PeelCount;
685
686 // Peeling does not update the PDT
687 PDT.recalculate(*FC0.Preheader->getParent());
688
689 FC0.updateAfterPeeling();
690
691 // In this case the iterations of the loop are constant, so the first
692 // loop will execute completely (will not jump from one of
693 // the peeled blocks to the second loop). Here we are updating the
694 // branch conditions of each of the peeled blocks, such that it will
695 // branch to its successor which is not the preheader of the second loop
696 // in the case of unguarded loops, or the succesors of the exit block of
697 // the first loop otherwise. Doing this update will ensure that the entry
698 // block of the first loop dominates the entry block of the second loop.
699 BasicBlock *BB =
700 FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
701 if (BB) {
703 SmallVector<Instruction *, 8> WorkList;
704 for (BasicBlock *Pred : predecessors(BB)) {
705 if (Pred != FC0.ExitBlock) {
706 WorkList.emplace_back(Pred->getTerminator());
707 TreeUpdates.emplace_back(
708 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
709 }
710 }
711 // Cannot modify the predecessors inside the above loop as it will cause
712 // the iterators to be nullptrs, causing memory errors.
713 for (Instruction *CurrentBranch : WorkList) {
714 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
715 if (Succ == BB)
716 Succ = CurrentBranch->getSuccessor(1);
717 ReplaceInstWithInst(CurrentBranch, UncondBrInst::Create(Succ));
718 }
719
720 DTU.applyUpdates(TreeUpdates);
721 DTU.flush();
722 }
724 dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
725 << " iterations from the first loop.\n"
726 "Both Loops have the same number of iterations now.\n");
727 }
728
729 /// Walk each set of strictly adjacent fusion candidates and attempt to fuse
730 /// them. This does a single linear traversal of all candidates in the list.
731 /// The conditions for legal fusion are checked at this point. If a pair of
732 /// fusion candidates passes all legality checks, they are fused together and
733 /// a new fusion candidate is created and added to the FusionCandidateList.
734 /// The original fusion candidates are then removed, as they are no longer
735 /// valid.
736 bool fuseCandidates() {
737 bool Fused = false;
738 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
739 for (auto &CandidateList : FusionCandidates) {
740 if (CandidateList.size() < 2)
741 continue;
742
743 LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate List:\n"
744 << CandidateList << "\n");
745
746 for (auto It = CandidateList.begin(), NextIt = std::next(It);
747 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
748
749 const FusionCandidate &FC0 = *It;
750 const FusionCandidate &FC1 = *NextIt;
751
752 assert(!LDT.isRemovedLoop(FC0.L) &&
753 "Should not have removed loops in CandidateList!");
754 assert(!LDT.isRemovedLoop(FC1.L) &&
755 "Should not have removed loops in CandidateList!");
756
757 LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0.dump();
758 dbgs() << " with\n"; FC1.dump(); dbgs() << "\n");
759
760 FC0.verify();
761 FC1.verify();
762
763 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
764 // Here we are checking that FC0 (the first loop) can be peeled, and
765 // the first loop has a larger trip count. In this case it is possible
766 // that the first loop is peeled to expose the fusion opportunity.
767 // Peeling the second loop is not currently supported.
768 bool WillPeel =
769 FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
770 *TCDifference <= static_cast<int64_t>(FusionPeelMaxCount);
771
772 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
773 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
774 "counts and peeling is not supported for this "
775 "case. Not fusing.\n");
776 ++NonEqualTripCount;
777 reportLoopFusion<OptimizationRemarkMissed>(
778 FC0, FC1, "NonEqualTripCount",
779 "Loop trip counts are not the same");
780 continue;
781 }
782
783 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
784 (FC0.GuardBranch && !FC1.GuardBranch)) {
785 LLVM_DEBUG(dbgs() << "The one of candidate is guarded while the "
786 "another one is not. Not fusing.\n");
787 ++OnlySecondCandidateIsGuarded;
788 reportLoopFusion<OptimizationRemarkMissed>(
789 FC0, FC1, "OnlySecondCandidateIsGuarded",
790 "The second candidate is guarded while the first one is not");
791 continue;
792 }
793
794 // If Loops are guarded, we expect the guards to be identical.
795 // Currently peeling is supported only for loops with constant
796 // iteration counts. If two loops have different loop guards
797 // there is no mechanism in loop fusion to make their fusion legal.
798 // The trivial case where the guards compare two constant values can be
799 // ignored. Those guards will be optimized away by other passes.
800 if (FC0.GuardBranch && FC1.GuardBranch &&
801 !haveIdenticalGuards(FC0, FC1)) {
802 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
803 "guards. Not Fusing.\n");
804 ++NonIdenticalGuards;
805 reportLoopFusion<OptimizationRemarkMissed>(
806 FC0, FC1, "NonIdenticalGuards",
807 "Candidates have different guards");
808 continue;
809 }
810
811 if (FC0.GuardBranch) {
812 assert(FC1.GuardBranch && "Expecting valid FC1 guard branch");
813
814 if (!isSafeToMoveBefore(*FC0.ExitBlock,
815 *FC1.ExitBlock->getFirstNonPHIOrDbg(), DT,
816 &PDT, &DI)) {
817 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
818 "instructions in exit block. Not fusing.\n");
819 ++NonEmptyExitBlock;
820 reportLoopFusion<OptimizationRemarkMissed>(
821 FC0, FC1, "NonEmptyExitBlock",
822 "Candidate has a non-empty exit block with "
823 "instructions that cannot be moved");
824 continue;
825 }
826
828 *FC1.GuardBranch->getParent(),
829 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
830 &DI)) {
831 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
832 "instructions in guard block. Not fusing.\n");
833 ++NonEmptyGuardBlock;
834 reportLoopFusion<OptimizationRemarkMissed>(
835 FC0, FC1, "NonEmptyGuardBlock",
836 "Candidate has a non-empty guard block with "
837 "instructions that cannot be moved");
838 continue;
839 }
840 }
841
842 // Check the dependencies across the loops and do not fuse if it would
843 // violate them.
844 if (!dependencesAllowFusion(FC0, FC1)) {
845 LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
846 ++InvalidDependencies;
847 reportLoopFusion<OptimizationRemarkMissed>(
848 FC0, FC1, "InvalidDependencies", "Dependencies prevent fusion");
849 continue;
850 }
851
852 // If the second loop has instructions in the pre-header, attempt to
853 // hoist them up to the first loop's pre-header or sink them into the
854 // body of the second loop.
855 SmallVector<Instruction *, 4> SafeToHoist;
856 SmallVector<Instruction *, 4> SafeToSink;
857 // At this point, this is the last remaining legality check.
858 // Which means if we can make this pre-header empty, we can fuse
859 // these loops
860 if (!isEmptyPreheader(FC1)) {
861 LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
862 "preheader.\n");
863
864 // If it is not safe to hoist/sink all instructions in the
865 // pre-header, we cannot fuse these loops.
866 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
867 SafeToSink)) {
868 LLVM_DEBUG(dbgs() << "Could not hoist/sink all instructions in "
869 "Fusion Candidate Pre-header.\n"
870 << "Not Fusing.\n");
871 ++NonEmptyPreheader;
872 reportLoopFusion<OptimizationRemarkMissed>(
873 FC0, FC1, "NonEmptyPreheader",
874 "Loop has a non-empty preheader with instructions that "
875 "cannot be moved");
876 continue;
877 }
878 }
879
880 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
881 LLVM_DEBUG(dbgs() << "\tFusion appears to be "
882 << (BeneficialToFuse ? "" : "un") << "profitable!\n");
883 if (!BeneficialToFuse) {
884 ++FusionNotBeneficial;
885 reportLoopFusion<OptimizationRemarkMissed>(
886 FC0, FC1, "FusionNotBeneficial", "Fusion is not beneficial");
887 continue;
888 }
889 // All analysis has completed and has determined that fusion is legal
890 // and profitable. At this point, start transforming the code and
891 // perform fusion.
892
893 // Execute the hoist/sink operations on preheader instructions
894 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
895
896 LLVM_DEBUG(dbgs() << "\tFusion is performed: " << FC0 << " and " << FC1
897 << "\n");
898
899 FusionCandidate FC0Copy = FC0;
900 // Peel the loop after determining that fusion is legal. The Loops
901 // will still be safe to fuse after the peeling is performed.
902 bool Peel = TCDifference && *TCDifference > 0;
903 if (Peel)
904 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
905
906 // Report fusion to the Optimization Remarks.
907 // Note this needs to be done *before* performFusion because
908 // performFusion will change the original loops, making it not
909 // possible to identify them after fusion is complete.
910 ++FuseCounter;
911 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
912 "FuseCounter", "Loops fused");
913
914 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
915 DT, &PDT, ORE, FC0Copy.PP);
916 FusedCand.verify();
917 assert(FusedCand.isEligibleForFusion(SE) &&
918 "Fused candidate should be eligible for fusion!");
919
920 // Notify the loop-depth-tree that these loops are not valid objects
921 LDT.removeLoop(FC1.L);
922
923 // Replace FC0 and FC1 with their fused loop
924 It = CandidateList.erase(It);
925 It = CandidateList.erase(It);
926 It = CandidateList.insert(It, FusedCand);
927
928 // Start from FusedCand in the next iteration
929 NextIt = It;
930
931 LLVM_DEBUG(dbgs() << "Candidate List (after fusion): " << CandidateList
932 << "\n");
933
934 Fused = true;
935 }
936 }
937 return Fused;
938 }
939
940 // Returns true if the instruction \p I can be hoisted to the end of the
941 // preheader of \p FC0. \p SafeToHoist contains the instructions that are
942 // known to be safe to hoist. The instructions encountered that cannot be
943 // hoisted are in \p NotHoisting.
944 // TODO: Move functionality into CodeMoverUtils
945 bool canHoistInst(Instruction &I,
946 const SmallVector<Instruction *, 4> &SafeToHoist,
947 const SmallVector<Instruction *, 4> &NotHoisting,
948 const FusionCandidate &FC0) const {
949 const BasicBlock *FC0PreheaderTarget = FC0.Preheader->getSingleSuccessor();
950 assert(FC0PreheaderTarget &&
951 "Expected single successor for loop preheader.");
952
953 for (Use &Op : I.operands()) {
954 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
955 bool OpHoisted = is_contained(SafeToHoist, OpInst);
956 // Check if we have already decided to hoist this operand. In this
957 // case, it does not dominate FC0 *yet*, but will after we hoist it.
958 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
959 return false;
960 }
961 }
962 }
963
964 // PHIs in FC1's header only have FC0 blocks as predecessors. PHIs
965 // cannot be hoisted and should be sunk to the exit of the fused loop.
966 if (isa<PHINode>(I))
967 return false;
968
969 // If this isn't a memory inst, hoisting is safe
970 if (!I.mayReadOrWriteMemory())
971 return true;
972
973 LLVM_DEBUG(dbgs() << "Checking if this mem inst can be hoisted.\n");
974 for (Instruction *NotHoistedInst : NotHoisting) {
975 if (auto D = DI.depends(&I, NotHoistedInst)) {
976 // Dependency is not read-before-write, write-before-read or
977 // write-before-write
978 if (D->isFlow() || D->isAnti() || D->isOutput()) {
979 LLVM_DEBUG(dbgs() << "Inst depends on an instruction in FC1's "
980 "preheader that is not being hoisted.\n");
981 return false;
982 }
983 }
984 }
985
986 for (Instruction *ReadInst : FC0.MemReads) {
987 if (auto D = DI.depends(ReadInst, &I)) {
988 // Dependency is not read-before-write
989 if (D->isAnti()) {
990 LLVM_DEBUG(dbgs() << "Inst depends on a read instruction in FC0.\n");
991 return false;
992 }
993 }
994 }
995
996 for (Instruction *WriteInst : FC0.MemWrites) {
997 if (auto D = DI.depends(WriteInst, &I)) {
998 // Dependency is not write-before-read or write-before-write
999 if (D->isFlow() || D->isOutput()) {
1000 LLVM_DEBUG(dbgs() << "Inst depends on a write instruction in FC0.\n");
1001 return false;
1002 }
1003 }
1004 }
1005 return true;
1006 }
1007
1008 // Returns true if the instruction \p I can be sunk to the top of the exit
1009 // block of \p FC1.
1010 // TODO: Move functionality into CodeMoverUtils
1011 bool canSinkInst(Instruction &I, const FusionCandidate &FC1) const {
1012 for (User *U : I.users()) {
1013 if (auto *UI{dyn_cast<Instruction>(U)}) {
1014 // Cannot sink if user in loop
1015 // If FC1 has phi users of this value, we cannot sink it into FC1.
1016 if (FC1.L->contains(UI)) {
1017 // Cannot hoist or sink this instruction. No hoisting/sinking
1018 // should take place, loops should not fuse
1019 return false;
1020 }
1021 }
1022 }
1023
1024 // If this isn't a memory inst, sinking is safe
1025 if (!I.mayReadOrWriteMemory())
1026 return true;
1027
1028 for (Instruction *ReadInst : FC1.MemReads) {
1029 if (auto D = DI.depends(&I, ReadInst)) {
1030 // Dependency is not write-before-read
1031 if (D->isFlow()) {
1032 LLVM_DEBUG(dbgs() << "Inst depends on a read instruction in FC1.\n");
1033 return false;
1034 }
1035 }
1036 }
1037
1038 for (Instruction *WriteInst : FC1.MemWrites) {
1039 if (auto D = DI.depends(&I, WriteInst)) {
1040 // Dependency is not write-before-write or read-before-write
1041 if (D->isOutput() || D->isAnti()) {
1042 LLVM_DEBUG(dbgs() << "Inst depends on a write instruction in FC1.\n");
1043 return false;
1044 }
1045 }
1046 }
1047
1048 return true;
1049 }
1050
1051 /// Collect instructions in the \p FC1 Preheader that can be hoisted
1052 /// to the \p FC0 Preheader or sunk into the \p FC1 Body
1053 bool collectMovablePreheaderInsts(
1054 const FusionCandidate &FC0, const FusionCandidate &FC1,
1055 SmallVector<Instruction *, 4> &SafeToHoist,
1056 SmallVector<Instruction *, 4> &SafeToSink) const {
1057 BasicBlock *FC1Preheader = FC1.Preheader;
1058 // Save the instructions that are not being hoisted, so we know not to hoist
1059 // mem insts that they dominate.
1060 SmallVector<Instruction *, 4> NotHoisting;
1061
1062 for (Instruction &I : *FC1Preheader) {
1063 // Can't move a branch
1064 if (&I == FC1Preheader->getTerminator())
1065 continue;
1066 // If the instruction has side-effects, give up.
1067 // TODO: The case of mayReadFromMemory we can handle but requires
1068 // additional work with a dependence analysis so for now we give
1069 // up on memory reads.
1070 if (I.mayThrow() || !I.willReturn()) {
1071 LLVM_DEBUG(dbgs() << "Inst: " << I << " may throw or won't return.\n");
1072 return false;
1073 }
1074
1075 LLVM_DEBUG(dbgs() << "Checking Inst: " << I << "\n");
1076
1077 if (I.isAtomic() || I.isVolatile()) {
1078 LLVM_DEBUG(
1079 dbgs() << "\tInstruction is volatile or atomic. Cannot move it.\n");
1080 return false;
1081 }
1082
1083 if (canHoistInst(I, SafeToHoist, NotHoisting, FC0)) {
1084 SafeToHoist.push_back(&I);
1085 LLVM_DEBUG(dbgs() << "\tSafe to hoist.\n");
1086 } else {
1087 LLVM_DEBUG(dbgs() << "\tCould not hoist. Trying to sink...\n");
1088 NotHoisting.push_back(&I);
1089
1090 if (canSinkInst(I, FC1)) {
1091 SafeToSink.push_back(&I);
1092 LLVM_DEBUG(dbgs() << "\tSafe to sink.\n");
1093 } else {
1094 LLVM_DEBUG(dbgs() << "\tCould not sink.\n");
1095 return false;
1096 }
1097 }
1098 }
1099 LLVM_DEBUG(
1100 dbgs() << "All preheader instructions could be sunk or hoisted!\n");
1101 return true;
1102 }
1103
1104 /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
1105 /// @p L1) allow loop fusion of @p L0 and @p L1.
1106 bool dependencesAllowFusion(const FusionCandidate &FC0,
1107 const FusionCandidate &FC1, Instruction &I0,
1108 Instruction &I1) {
1109#ifndef NDEBUG
1111 LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << "\n");
1112 }
1113#endif
1114 auto DepResult = DI.depends(&I0, &I1);
1115 if (!DepResult)
1116 return true;
1117 // If two stores write the same SSA value, fusion is safe regardless of
1118 // aliasing - writing the same value twice is idempotent.
1119 if (isa<StoreInst>(I0) && isa<StoreInst>(I1)) {
1120 auto *S0 = cast<StoreInst>(&I0);
1121 auto *S1 = cast<StoreInst>(&I1);
1122 if (S0->getValueOperand() == S1->getValueOperand())
1123 return true;
1124 }
1125#ifndef NDEBUG
1127 LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
1128 dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
1129 << (DepResult->isOrdered() ? "true" : "false")
1130 << "]\n");
1131 LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
1132 << "\n");
1133 }
1134#endif
1135 unsigned Levels = DepResult->getLevels();
1136 unsigned SameSDLevels = DepResult->getSameSDLevels();
1137 unsigned CurLoopLevel = FC0.L->getLoopDepth();
1138
1139 // Check if DA is missing info regarding the current loop level
1140 if (CurLoopLevel > Levels + SameSDLevels)
1141 return false;
1142
1143 // Iterating over the outer levels.
1144 for (unsigned Level = 1; Level <= std::min(CurLoopLevel - 1, Levels);
1145 ++Level) {
1146 unsigned Direction = DepResult->getDirection(Level, false);
1147
1148 // Check if the direction vector does not include equality. If an outer
1149 // loop has a non-equal direction, outer indicies are different and it
1150 // is safe to fuse.
1152 LLVM_DEBUG(dbgs() << "Safe to fuse due to non-equal acceses in the "
1153 "outer loops\n");
1154 NumDA++;
1155 return true;
1156 }
1157 }
1158
1159 assert(CurLoopLevel > Levels && "Fusion candidates are not separated");
1160
1161 if (DepResult->isScalar(CurLoopLevel, true)) {
1162 if (DepResult->isInput() || DepResult->isOutput()) {
1163 LLVM_DEBUG(dbgs() << "Safe to fuse due to a loop-invariant "
1164 << (DepResult->isInput() ? "input" : "output")
1165 << " dependency\n");
1166 NumDA++;
1167 return true;
1168 }
1169 LLVM_DEBUG(
1170 dbgs() << "Not safe to fuse due to a scalar flow dependency\n");
1171 return false;
1172 }
1173
1174 unsigned CurDir = DepResult->getDirection(CurLoopLevel, true);
1175
1176 // Check if the direction vector does not include greater direction. In
1177 // that case, the dependency is not a backward loop-carried and is legal
1178 // to fuse. For example here we have a forward dependency
1179 // for (int i = 0; i < n; i++)
1180 // A[i] = ...;
1181 // for (int i = 0; i < n; i++)
1182 // ... = A[i-1];
1183 if (!(CurDir & Dependence::DVEntry::GT)) {
1184 LLVM_DEBUG(dbgs() << "Safe to fuse with no backward loop-carried "
1185 "dependency\n");
1186 NumDA++;
1187 return true;
1188 }
1189
1190 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1191 LLVM_DEBUG(dbgs() << "TODO: Implement pred/succ dependence handling!\n");
1192
1193 return false;
1194 }
1195
1196 /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
1197 bool dependencesAllowFusion(const FusionCandidate &FC0,
1198 const FusionCandidate &FC1) {
1199 LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
1200 << "\n");
1201 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
1202 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1203
1204 // Walk through all uses in FC1. For each use, find the reaching def.
1205 // If the def is located in FC0 then it is not safe to fuse.
1206 for (BasicBlock *BB : FC1.L->blocks())
1207 for (Instruction &I : *BB)
1208 for (auto &Op : I.operands())
1209 if (Instruction *Def = dyn_cast<Instruction>(Op))
1210 if (FC0.L->contains(Def->getParent())) {
1211 return false;
1212 }
1213
1214 for (Instruction *WriteL0 : FC0.MemWrites) {
1215 for (Instruction *WriteL1 : FC1.MemWrites)
1216 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1217 return false;
1218 }
1219 for (Instruction *ReadL1 : FC1.MemReads)
1220 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1221 return false;
1222 }
1223 }
1224
1225 // Write-write and write-read pairs are already covered above; only the
1226 // read-before-write pairs from FC0 reads to FC1 writes remain.
1227 for (Instruction *ReadL0 : FC0.MemReads)
1228 for (Instruction *WriteL1 : FC1.MemWrites)
1229 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1230 return false;
1231 }
1232
1233 return true;
1234 }
1235
1236 /// Determine if two fusion candidates are strictly adjacent in the CFG.
1237 ///
1238 /// This method will determine if there are additional basic blocks in the CFG
1239 /// between the exit of \p FC0 and the entry of \p FC1.
1240 /// If the two candidates are guarded loops, then it checks whether the
1241 /// exit block of the \p FC0 is the predecessor of the \p FC1 preheader. This
1242 /// implicitly ensures that the non-loop successor of the \p FC0 guard branch
1243 /// is the entry block of \p FC1. If not, then the loops are not adjacent. If
1244 /// the two candidates are not guarded loops, then it checks whether the exit
1245 /// block of \p FC0 is the preheader of \p FC1.
1246 /// Strictly means there is no predecessor for FC1 unless it is from FC0,
1247 /// i.e., FC0 dominates FC1.
1248 bool isStrictlyAdjacent(const FusionCandidate &FC0,
1249 const FusionCandidate &FC1) const {
1250 // If the successor of the guard branch is FC1, then the loops are adjacent
1251 if (FC0.GuardBranch)
1252 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1253 FC0.ExitBlock->getSingleSuccessor() == FC1.getEntryBlock();
1254 return FC0.ExitBlock == FC1.getEntryBlock();
1255 }
1256
1257 bool isEmptyPreheader(const FusionCandidate &FC) const {
1258 return FC.Preheader->size() == 1;
1259 }
1260
1261 /// Hoist \p FC1 Preheader instructions to \p FC0 Preheader
1262 /// and sink others into the body of \p FC1.
1263 void movePreheaderInsts(const FusionCandidate &FC0,
1264 const FusionCandidate &FC1,
1265 SmallVector<Instruction *, 4> &HoistInsts,
1266 SmallVector<Instruction *, 4> &SinkInsts) const {
1267 // All preheader instructions except the branch must be hoisted or sunk
1268 assert(HoistInsts.size() + SinkInsts.size() == FC1.Preheader->size() - 1 &&
1269 "Attempting to sink and hoist preheader instructions, but not all "
1270 "the preheader instructions are accounted for.");
1271
1272 NumHoistedInsts += HoistInsts.size();
1273 NumSunkInsts += SinkInsts.size();
1274
1276 if (!HoistInsts.empty())
1277 dbgs() << "Hoisting: \n";
1278 for (Instruction *I : HoistInsts)
1279 dbgs() << *I << "\n";
1280 if (!SinkInsts.empty())
1281 dbgs() << "Sinking: \n";
1282 for (Instruction *I : SinkInsts)
1283 dbgs() << *I << "\n";
1284 });
1285
1286 for (Instruction *I : HoistInsts) {
1287 assert(I->getParent() == FC1.Preheader);
1288 I->moveBefore(*FC0.Preheader,
1289 FC0.Preheader->getTerminator()->getIterator());
1290 }
1291 // insert instructions in reverse order to maintain dominance relationship
1292 for (Instruction *I : reverse(SinkInsts)) {
1293 assert(I->getParent() == FC1.Preheader);
1294 if (isa<PHINode>(I)) {
1295 // The Phis to be sunk should have only one incoming value, as is
1296 // assured by the condition that the second loop is dominated by the
1297 // first one which is enforced by isStrictlyAdjacent().
1298 // Replace the phi uses with the corresponding incoming value to clean
1299 // up the code.
1300 assert(cast<PHINode>(I)->getNumIncomingValues() == 1 &&
1301 "Expected the sunk PHI node to have 1 incoming value.");
1302 I->replaceAllUsesWith(I->getOperand(0));
1303 I->eraseFromParent();
1304 } else
1305 I->moveBefore(*FC1.ExitBlock, FC1.ExitBlock->getFirstInsertionPt());
1306 }
1307 }
1308
1309 /// Determine if two fusion candidates have identical guards
1310 ///
1311 /// This method will determine if two fusion candidates have the same guards.
1312 /// The guards are considered the same if:
1313 /// 1. The instructions to compute the condition used in the compare are
1314 /// identical.
1315 /// 2. The successors of the guard have the same flow into/around the loop.
1316 /// If the compare instructions are identical, then the first successor of the
1317 /// guard must go to the same place (either the preheader of the loop or the
1318 /// NonLoopBlock). In other words, the first successor of both loops must
1319 /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
1320 /// the NonLoopBlock). The same must be true for the second successor.
1321 bool haveIdenticalGuards(const FusionCandidate &FC0,
1322 const FusionCandidate &FC1) const {
1323 assert(FC0.GuardBranch && FC1.GuardBranch &&
1324 "Expecting FC0 and FC1 to be guarded loops.");
1325
1326 auto *FC0CmpInst = dyn_cast<Instruction>(FC0.GuardBranch->getCondition());
1327 auto *FC1CmpInst = dyn_cast<Instruction>(FC1.GuardBranch->getCondition());
1328 if ((!FC0CmpInst || !FC1CmpInst) &&
1329 FC0.GuardBranch->getCondition() != FC1.GuardBranch->getCondition())
1330 return false;
1331
1332 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1333 return false;
1334
1335 // The compare instructions are identical.
1336 // Now make sure the successor of the guards have the same flow into/around
1337 // the loop
1338 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1339 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1340 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1341 }
1342
1343 /// Modify the latch branch of FC to be unconditional since successors of the
1344 /// branch are the same.
1345 void simplifyLatchBranch(const FusionCandidate &FC) const {
1346 CondBrInst *FCLatchBranch = dyn_cast<CondBrInst>(FC.Latch->getTerminator());
1347 if (FCLatchBranch) {
1348 assert(FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
1349 "Expecting the two successors of FCLatchBranch to be the same");
1350 UncondBrInst *NewBranch =
1351 UncondBrInst::Create(FCLatchBranch->getSuccessor(0));
1352 ReplaceInstWithInst(FCLatchBranch, NewBranch);
1353 }
1354 }
1355
1356 /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique
1357 /// successor, then merge FC0.Latch with its unique successor.
1358 void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1359 moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI, SE);
1360 if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
1361 MergeBlockIntoPredecessor(Succ, &DTU, &LI);
1362 DTU.flush();
1363 }
1364 }
1365
1366 /// Move FC1's header PHIs into FC0's header, insert the loop-carried PHIs
1367 /// needed to keep SSA valid when FC0 exits without taking its back-edge, and
1368 /// rewire both latches to form the fused loop. Latch dominator-tree updates
1369 /// are appended to \p TreeUpdates for the caller to apply.
1370 void rewireFusedHeaderPHIsAndLatches(
1371 const FusionCandidate &FC0, const FusionCandidate &FC1,
1372 const SmallVectorImpl<PHINode *> &OriginalFC0PHIs,
1373 SmallVectorImpl<DominatorTree::UpdateType> &TreeUpdates) {
1374 // Moves the phi nodes from the second to the first loops header block.
1375 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1376 if (SE.isSCEVable(PHI->getType()))
1377 SE.forgetValue(PHI);
1378 if (PHI->hasNUsesOrMore(1))
1379 PHI->moveBefore(FC0.Header->getFirstInsertionPt());
1380 else
1381 PHI->eraseFromParent();
1382 }
1383
1384 // Introduce new phi nodes in the second loop header to ensure
1385 // exiting the first and jumping to the header of the second does not break
1386 // the SSA property of the phis originally in the first loop. See also the
1387 // comment above.
1388 BasicBlock::iterator L1HeaderIP = FC1.Header->begin();
1389 for (PHINode *LCPHI : OriginalFC0PHIs) {
1390 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1391 assert(L1LatchBBIdx >= 0 &&
1392 "Expected loop carried value to be rewired at this point!");
1393
1394 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1395
1396 PHINode *L1HeaderPHI =
1397 PHINode::Create(LCV->getType(), 2, LCPHI->getName() + ".afterFC0");
1398 L1HeaderPHI->insertBefore(L1HeaderIP);
1399 L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1400 L1HeaderPHI->addIncoming(PoisonValue::get(LCV->getType()),
1401 FC0.ExitingBlock);
1402
1403 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1404 }
1405
1406 // Replace latch terminator destinations.
1407 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1408 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1409
1410 // Modify the latch branch of FC0 to be unconditional as both successors of
1411 // the branch are the same.
1412 simplifyLatchBranch(FC0);
1413
1414 // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1415 // performed the updates above.
1416 if (FC0.Latch != FC0.ExitingBlock)
1417 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1418 DominatorTree::Insert, FC0.Latch, FC1.Header));
1419
1420 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1421 FC0.Latch, FC0.Header));
1422 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1423 FC1.Latch, FC0.Header));
1424 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1425 FC1.Latch, FC1.Header));
1426 }
1427
1428 /// Forget cached SCEV state for both loops, move all of FC1's blocks and
1429 /// child loops into FC0, erase the now-empty FC1, and merge the latches.
1430 /// Returns the fused loop (FC0.L).
1431 Loop *finalizeFusedLoop(const FusionCandidate &FC0,
1432 const FusionCandidate &FC1) {
1433 // Is there a way to keep SE up-to-date so we don't need to forget the loops
1434 // and rebuild the information in subsequent passes of fusion?
1435 // Note: Need to forget the loops before merging the loop latches, as
1436 // mergeLatch may remove the only block in FC1.
1437 SE.forgetLoop(FC1.L);
1438 SE.forgetLoop(FC0.L);
1439
1440 // Merge the loops.
1441 SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
1442 for (BasicBlock *BB : Blocks) {
1443 FC0.L->addBlockEntry(BB);
1444 FC1.L->removeBlockFromLoop(BB);
1445 if (LI.getLoopFor(BB) != FC1.L)
1446 continue;
1447 LI.changeLoopFor(BB, FC0.L);
1448 }
1449 while (!FC1.L->isInnermost()) {
1450 const auto &ChildLoopIt = FC1.L->begin();
1451 Loop *ChildLoop = *ChildLoopIt;
1452 FC1.L->removeChildLoop(ChildLoopIt);
1453 FC0.L->addChildLoop(ChildLoop);
1454 }
1455
1456 // Delete the now empty loop L1.
1457 LI.erase(FC1.L);
1458
1459 // Forget block dispositions as well, so that there are no dangling
1460 // pointers to erased/free'ed blocks. It should be done after mergeLatch()
1461 // since merging the latches may affect the dispositions.
1462 SE.forgetBlockAndLoopDispositions();
1463
1464 // Move instructions from FC0.Latch to FC1.Latch.
1465 // Note: mergeLatch requires an updated DT.
1466 mergeLatch(FC0, FC1);
1467
1468#ifndef NDEBUG
1469 assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1470 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1471 assert(PDT.verify());
1472 LI.verify();
1473 SE.verify();
1474#endif
1475
1476 LLVM_DEBUG(dbgs() << "Fusion done:\n");
1477
1478 return FC0.L;
1479 }
1480
1481 /// Fuse two fusion candidates, creating a new fused loop.
1482 ///
1483 /// This method contains the mechanics of fusing two loops, represented by \p
1484 /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
1485 /// postdominates \p FC0 (making them control flow equivalent). It also
1486 /// assumes that the other conditions for fusion have been met: adjacent,
1487 /// identical trip counts, and no negative distance dependencies exist that
1488 /// would prevent fusion. Thus, there is no checking for these conditions in
1489 /// this method.
1490 ///
1491 /// Fusion is performed by rewiring the CFG to update successor blocks of the
1492 /// components of tho loop. Specifically, the following changes are done:
1493 ///
1494 /// 1. The preheader of \p FC1 is removed as it is no longer necessary
1495 /// (because it is currently only a single statement block).
1496 /// 2. The latch of \p FC0 is modified to jump to the header of \p FC1.
1497 /// 3. The latch of \p FC1 i modified to jump to the header of \p FC0.
1498 /// 4. All blocks from \p FC1 are removed from FC1 and added to FC0.
1499 ///
1500 /// All of these modifications are done with dominator tree updates, thus
1501 /// keeping the dominator (and post dominator) information up-to-date.
1502 ///
1503 /// This can be improved in the future by actually merging blocks during
1504 /// fusion. For example, the preheader of \p FC1 can be merged with the
1505 /// preheader of \p FC0. This would allow loops with more than a single
1506 /// statement in the preheader to be fused. Similarly, the latch blocks of the
1507 /// two loops could also be fused into a single block. This will require
1508 /// analysis to prove it is safe to move the contents of the block past
1509 /// existing code, which currently has not been implemented.
1510 Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1511 assert(FC0.isValid() && FC1.isValid() &&
1512 "Expecting valid fusion candidates");
1513
1514 LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
1515 dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
1516
1517 // Move instructions from the preheader of FC1 to the end of the preheader
1518 // of FC0.
1519 moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI, SE);
1520
1521 // Fusing guarded loops is handled slightly differently than non-guarded
1522 // loops and has been broken out into a separate method instead of trying to
1523 // intersperse the logic within a single method.
1524 if (FC0.GuardBranch)
1525 return fuseGuardedLoops(FC0, FC1);
1526
1527 assert(FC1.Preheader ==
1528 (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
1529 assert(FC1.Preheader->size() == 1 &&
1530 FC1.Preheader->getSingleSuccessor() == FC1.Header);
1531
1532 // Remember the phi nodes originally in the header of FC0 in order to rewire
1533 // them later. However, this is only necessary if the new loop carried
1534 // values might not dominate the exiting branch. While we do not generally
1535 // test if this is the case but simply insert intermediate phi nodes, we
1536 // need to make sure these intermediate phi nodes have different
1537 // predecessors. To this end, we filter the special case where the exiting
1538 // block is the latch block of the first loop. Nothing needs to be done
1539 // anyway as all loop carried values dominate the latch and thereby also the
1540 // exiting branch.
1541 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1542 if (FC0.ExitingBlock != FC0.Latch)
1543 for (PHINode &PHI : FC0.Header->phis())
1544 OriginalFC0PHIs.push_back(&PHI);
1545
1546 // Replace incoming blocks for header PHIs first.
1547 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1548 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1549
1550 // Then modify the control flow and update DT and PDT.
1552
1553 // The old exiting block of the first loop (FC0) has to jump to the header
1554 // of the second as we need to execute the code in the second header block
1555 // regardless of the trip count. That is, if the trip count is 0, so the
1556 // back edge is never taken, we still have to execute both loop headers,
1557 // especially (but not only!) if the second is a do-while style loop.
1558 // However, doing so might invalidate the phi nodes of the first loop as
1559 // the new values do only need to dominate their latch and not the exiting
1560 // predicate. To remedy this potential problem we always introduce phi
1561 // nodes in the header of the second loop later that select the loop carried
1562 // value, if the second header was reached through an old latch of the
1563 // first, or undef otherwise. This is sound as exiting the first implies the
1564 // second will exit too, __without__ taking the back-edge. [Their
1565 // trip-counts are equal after all.
1566 // KB: Would this sequence be simpler to just make FC0.ExitingBlock go
1567 // to FC1.Header? I think this is basically what the three sequences are
1568 // trying to accomplish; however, doing this directly in the CFG may mean
1569 // the DT/PDT becomes invalid
1570 if (!FC0.Peeled) {
1571 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1572 FC1.Header);
1573 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1574 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1575 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1576 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1577 } else {
1578 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1579 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1580
1581 // Remove the ExitBlock of the first Loop (also not needed)
1582 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1583 FC1.Header);
1584 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1585 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1586 FC0.ExitBlock->getTerminator()->eraseFromParent();
1587 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1588 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1589 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1590 }
1591
1592 // The pre-header of L1 is not necessary anymore.
1593 assert(pred_empty(FC1.Preheader));
1594 FC1.Preheader->getTerminator()->eraseFromParent();
1595 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1596 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1597 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1598
1599 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1600
1601 // Update DT/PDT
1602 DTU.applyUpdates(TreeUpdates);
1603
1604 LI.removeBlock(FC1.Preheader);
1605 DTU.deleteBB(FC1.Preheader);
1606 if (FC0.Peeled) {
1607 LI.removeBlock(FC0.ExitBlock);
1608 DTU.deleteBB(FC0.ExitBlock);
1609 }
1610
1611 DTU.flush();
1612
1613 return finalizeFusedLoop(FC0, FC1);
1614 }
1615
1616 /// Report details on loop fusion opportunities.
1617 ///
1618 /// This template function can be used to report both successful and missed
1619 /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
1620 /// be one of:
1621 /// - OptimizationRemarkMissed to report when loop fusion is unsuccessful
1622 /// given two valid fusion candidates.
1623 /// - OptimizationRemark to report successful fusion of two fusion
1624 /// candidates.
1625 /// The remarks will be printed using the form:
1626 /// <path/filename>:<line number>:<column number>: [<function name>]:
1627 /// <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
1628 template <typename RemarkKind>
1629 void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
1630 StringRef RemarkName, StringRef RemarkMsg) {
1631 assert(FC0.Preheader && FC1.Preheader &&
1632 "Expecting valid fusion candidates");
1633 using namespace ore;
1634 ORE.emit(
1635 RemarkKind(DEBUG_TYPE, RemarkName, FC0.L->getStartLoc(), FC0.Preheader)
1636 << "[" << FC0.Preheader->getParent()->getName()
1637 << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName())) << " and "
1638 << NV("Cand2", StringRef(FC1.Preheader->getName())) << ": "
1639 << RemarkMsg);
1640 }
1641
1642 /// Fuse two guarded fusion candidates, creating a new fused loop.
1643 ///
1644 /// Fusing guarded loops is handled much the same way as fusing non-guarded
1645 /// loops. The rewiring of the CFG is slightly different though, because of
1646 /// the presence of the guards around the loops and the exit blocks after the
1647 /// loop body. As such, the new loop is rewired as follows:
1648 /// 1. Keep the guard branch from FC0 and use the non-loop block target
1649 /// from the FC1 guard branch.
1650 /// 2. Remove the exit block from FC0 (this exit block should be empty
1651 /// right now).
1652 /// 3. Remove the guard branch for FC1
1653 /// 4. Remove the preheader for FC1.
1654 /// The exit block successor for the latch of FC0 is updated to be the header
1655 /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
1656 /// be the header of FC0, thus creating the fused loop.
1657 Loop *fuseGuardedLoops(const FusionCandidate &FC0,
1658 const FusionCandidate &FC1) {
1659 assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
1660
1661 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1662 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1663 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1664 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1665 BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
1666
1667 // Move instructions from the exit block of FC0 to the beginning of the exit
1668 // block of FC1, in the case that the FC0 loop has not been peeled. In the
1669 // case that FC0 loop is peeled, then move the instructions of the successor
1670 // of the FC0 Exit block to the beginning of the exit block of FC1.
1672 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1673 DT, PDT, DI, SE);
1674
1675 // Move instructions from the guard block of FC1 to the end of the guard
1676 // block of FC0.
1677 moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI, SE);
1678
1679 assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
1680
1682
1683 ////////////////////////////////////////////////////////////////////////////
1684 // Update the Loop Guard
1685 ////////////////////////////////////////////////////////////////////////////
1686 // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
1687 // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
1688 // Thus, one path from the guard goes to the preheader for FC0 (and thus
1689 // executes the new fused loop) and the other path goes to the NonLoopBlock
1690 // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1691 FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
1692 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1693
1694 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1695 BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
1696
1697 // The guard of FC1 is not necessary anymore.
1698 FC1.GuardBranch->eraseFromParent();
1699 new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
1700
1701 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1702 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1703 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1704 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1705 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1706 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1707 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1708 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1709
1710 if (FC0.Peeled) {
1711 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1712 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1713 // Remove the Block after the ExitBlock of FC0
1714 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1715 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1716 FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
1717 new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
1718 FC0ExitBlockSuccessor);
1719 }
1720
1721 assert(pred_empty(FC1GuardBlock) &&
1722 "Expecting guard block to have no predecessors");
1723 assert(succ_empty(FC1GuardBlock) &&
1724 "Expecting guard block to have no successors");
1725
1726 // Remember the phi nodes originally in the header of FC0 in order to rewire
1727 // them later. However, this is only necessary if the new loop carried
1728 // values might not dominate the exiting branch. While we do not generally
1729 // test if this is the case but simply insert intermediate phi nodes, we
1730 // need to make sure these intermediate phi nodes have different
1731 // predecessors. To this end, we filter the special case where the exiting
1732 // block is the latch block of the first loop. Nothing needs to be done
1733 // anyway as all loop carried values dominate the latch and thereby also the
1734 // exiting branch.
1735 // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
1736 // (because the loops are rotated. Thus, nothing will ever be added to
1737 // OriginalFC0PHIs.
1738 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1739 if (FC0.ExitingBlock != FC0.Latch)
1740 for (PHINode &PHI : FC0.Header->phis())
1741 OriginalFC0PHIs.push_back(&PHI);
1742
1743 assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
1744
1745 // Replace incoming blocks for header PHIs first.
1746 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1747 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1748
1749 // The old exiting block of the first loop (FC0) has to jump to the header
1750 // of the second as we need to execute the code in the second header block
1751 // regardless of the trip count. That is, if the trip count is 0, so the
1752 // back edge is never taken, we still have to execute both loop headers,
1753 // especially (but not only!) if the second is a do-while style loop.
1754 // However, doing so might invalidate the phi nodes of the first loop as
1755 // the new values do only need to dominate their latch and not the exiting
1756 // predicate. To remedy this potential problem we always introduce phi
1757 // nodes in the header of the second loop later that select the loop carried
1758 // value, if the second header was reached through an old latch of the
1759 // first, or undef otherwise. This is sound as exiting the first implies the
1760 // second will exit too, __without__ taking the back-edge (their
1761 // trip-counts are equal after all).
1762 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1763 FC1.Header);
1764
1765 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1766 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1767 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1768 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1769
1770 // Remove FC0 Exit Block
1771 // The exit block for FC0 is no longer needed since control will flow
1772 // directly to the header of FC1. Since it is an empty block, it can be
1773 // removed at this point.
1774 // TODO: In the future, we can handle non-empty exit blocks my merging any
1775 // instructions from FC0 exit block into FC1 exit block prior to removing
1776 // the block.
1777 assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
1778 FC0.ExitBlock->getTerminator()->eraseFromParent();
1779 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1780
1781 // Remove FC1 Preheader
1782 // The pre-header of L1 is not necessary anymore.
1783 assert(pred_empty(FC1.Preheader));
1784 FC1.Preheader->getTerminator()->eraseFromParent();
1785 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1786 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1787 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1788
1789 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1790
1791 // All done
1792 // Apply the updates to the Dominator Tree and cleanup.
1793
1794 assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
1795 assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
1796
1797 // Update DT/PDT
1798 DTU.applyUpdates(TreeUpdates);
1799
1800 LI.removeBlock(FC1GuardBlock);
1801 LI.removeBlock(FC1.Preheader);
1802 LI.removeBlock(FC0.ExitBlock);
1803 if (FC0.Peeled) {
1804 LI.removeBlock(FC0ExitBlockSuccessor);
1805 DTU.deleteBB(FC0ExitBlockSuccessor);
1806 }
1807 DTU.deleteBB(FC1GuardBlock);
1808 DTU.deleteBB(FC1.Preheader);
1809 DTU.deleteBB(FC0.ExitBlock);
1810 DTU.flush();
1811
1812 return finalizeFusedLoop(FC0, FC1);
1813 }
1814};
1815} // namespace
1816
1818 auto &LI = AM.getResult<LoopAnalysis>(F);
1819 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1820 auto &DI = AM.getResult<DependenceAnalysis>(F);
1821 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1822 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1824 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1826
1827 // Ensure loops are in simplifed form which is a pre-requisite for loop fusion
1828 // pass. Added only for new PM since the legacy PM has already added
1829 // LoopSimplify pass as a dependency.
1830 bool Changed = false;
1831 for (auto &L : LI) {
1832 Changed |=
1833 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
1834 }
1835 if (Changed)
1836 PDT.recalculate(F);
1837
1838 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, AC, TTI);
1839 Changed |= LF.fuseLoops(F);
1840 if (!Changed)
1841 return PreservedAnalyses::all();
1842
1847 PA.preserve<LoopAnalysis>();
1848 return PA;
1849}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
Rewrite undef for PHI
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
#define DEBUG_TYPE
static cl::opt< uint32_t > FusionPeelMaxCount("loop-fusion-peel-max-count", cl::init(0), cl::Hidden, cl::desc("Max number of iterations to be peeled from a loop, such that " "fusion can take place"))
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
Definition LoopFuse.cpp:396
std::list< FusionCandidate > FusionCandidateList
Definition LoopFuse.cpp:367
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
Definition LoopFuse.cpp:368
static void printLoopVector(const LoopVector &LV)
Definition LoopFuse.cpp:371
SmallVector< Loop *, 4 > LoopVector
Definition LoopFuse.cpp:362
static cl::opt< bool > VerboseFusionDebugging("loop-fusion-verbose-debug", cl::desc("Enable verbose debugging for Loop Fusion"), cl::Hidden, cl::init(false))
#define DEBUG_TYPE
Definition LoopFuse.cpp:70
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ppc ctr loops verify
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const Instruction & front() const
Definition BasicBlock.h:469
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:467
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
AnalysisPass to compute dependence information in a function.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
unsigned getLoopDepth() const
Return the nesting level of this loop.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
iterator begin() const
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
reverse_iterator rend() const
reverse_iterator rbegin() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:695
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
bool succ_empty(const Instruction *I)
Definition CFG.h:141
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
LLVM_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
LLVM_ABI bool canPeel(const Loop *L)
Definition LoopPeel.cpp:97
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint, DominatorTree &DT, const PostDominatorTree *PDT=nullptr, DependenceInfo *DI=nullptr, bool CheckForEntireBlock=false)
Return true if I can be safely moved before InsertPoint.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...