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