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