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