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 "ScalarOptions.h"
49#include "llvm/ADT/DenseMap.h"
51#include "llvm/ADT/Statistic.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/Verifier.h"
65#include "llvm/Support/Debug.h"
72#include <list>
73#include <tuple>
74
75using namespace llvm;
76
77#define DEBUG_TYPE "loop-fusion"
78
79STATISTIC(FuseCounter, "Loops fused");
80STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
81STATISTIC(InvalidLoopStructure, "Loop has invalid structure");
82STATISTIC(AddressTakenBB, "Basic block has address taken");
83STATISTIC(MayThrowException, "Loop may throw an exception");
84STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
85STATISTIC(ContainsAtomicAccess, "Loop contains an atomic access");
86STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
87STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
88STATISTIC(UnknownTripCount, "Loop has unknown trip count");
89STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
90STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
92 NonEmptyPreheader,
93 "Loop has a non-empty preheader with instructions that cannot be moved");
94STATISTIC(InsufficientReuse,
95 "Fusion has insufficient cross-loop reused values");
96STATISTIC(NonIdenticalGuards, "Candidates have different guards");
97STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
98 "instructions that cannot be moved");
99STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
100 "instructions that cannot be moved");
101STATISTIC(NotRotated, "Candidate is not rotated");
102STATISTIC(OnlySecondCandidateIsGuarded,
103 "The second candidate is guarded while the first one is not");
104STATISTIC(NumHoistedInsts, "Number of hoisted preheader instructions.");
105STATISTIC(NumSunkInsts, "Number of sunk preheader instructions.");
106STATISTIC(NumDA, "DA checks passed");
107
108namespace {
109
110using ReusedValueSet = SmallPtrSet<const Instruction *, 4>;
111
112/// This class is used to represent a candidate for loop fusion. When it is
113/// constructed, it checks the conditions for loop fusion to ensure that it
114/// represents a valid candidate. It caches several parts of a loop that are
115/// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
116/// of continually querying the underlying Loop to retrieve these values. It is
117/// assumed these will not change throughout loop fusion.
118///
119/// The invalidate method should be used to indicate that the FusionCandidate is
120/// no longer a valid candidate for fusion. Similarly, the isValid() method can
121/// be used to ensure that the FusionCandidate is still valid for fusion.
122struct FusionCandidate {
123 /// Cache of parts of the loop used throughout loop fusion. These should not
124 /// need to change throughout the analysis and transformation.
125 /// These parts are cached to avoid repeatedly looking up in the Loop class.
126
127 /// Preheader of the loop this candidate represents
128 BasicBlock *Preheader;
129 /// Header of the loop this candidate represents
130 BasicBlock *Header;
131 /// Blocks in the loop that exit the loop
132 BasicBlock *ExitingBlock;
133 /// The successor block of this loop (where the exiting blocks go to)
134 BasicBlock *ExitBlock;
135 /// Latch of the loop
136 BasicBlock *Latch;
137 /// The loop that this fusion candidate represents
138 Loop *L;
139 /// Vector of instructions in this loop that read from memory
141 /// Vector of instructions in this loop that write to memory
143 /// Are all of the members of this fusion candidate still valid
144 bool Valid;
145 /// Guard branch of the loop, if it exists
146 CondBrInst *GuardBranch;
147 /// Peeling Paramaters of the Loop.
149 /// Can you Peel this Loop?
150 bool AbleToPeel;
151 /// Has this loop been Peeled
152 bool Peeled;
153
154 DominatorTree &DT;
155 const PostDominatorTree *PDT;
156
158
159 FusionCandidate(Loop *L, DominatorTree &DT, const PostDominatorTree *PDT,
161 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
162 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
163 Latch(L->getLoopLatch()), L(L), Valid(true),
164 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
165 Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
166
167 // Walk over all blocks in the loop and check for conditions that may
168 // prevent fusion. For each block, walk over all instructions and collect
169 // the memory reads and writes If any instructions that prevent fusion are
170 // found, invalidate this object and return.
171 for (BasicBlock *BB : L->blocks()) {
172 if (BB->hasAddressTaken()) {
173 invalidate();
174 ++AddressTakenBB;
175 reportInvalidCandidate("AddressTakenBB",
176 "Basic block has address taken");
177 return;
178 }
179
180 for (Instruction &I : *BB) {
181 if (I.mayThrow()) {
182 invalidate();
183 ++MayThrowException;
184 reportInvalidCandidate("MayThrowException",
185 "Loop may throw an exception");
186 return;
187 }
188 if (I.isVolatile()) {
189 invalidate();
190 ++ContainsVolatileAccess;
191 reportInvalidCandidate("ContainsVolatileAccess",
192 "Loop contains a volatile access");
193 return;
194 }
195 // Atomic accesses impose ordering/synchronization constraints that the
196 // dependence analysis used for fusion does not model, so reordering
197 // them across the fused body could be unsafe.
198 if (I.isAtomic()) {
199 invalidate();
200 ++ContainsAtomicAccess;
201 reportInvalidCandidate("ContainsAtomicAccess",
202 "Loop contains an atomic access");
203 return;
204 }
205 if (I.mayWriteToMemory())
206 MemWrites.push_back(&I);
207 if (I.mayReadFromMemory())
208 MemReads.push_back(&I);
209 }
210 }
211 }
212
213 /// Check if all members of the class are valid.
214 bool isValid() const {
215 return Preheader && ExitingBlock && ExitBlock && Latch && L &&
216 !L->isInvalid() && Valid;
217 }
218
219 /// Verify that all members are in sync with the Loop object.
220 void verify() const {
221 assert(isValid() && "Candidate is not valid!!");
222 assert(!L->isInvalid() && "Loop is invalid!");
223 assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
224 assert(Header == L->getHeader() && "Header is out of sync");
225 assert(ExitingBlock == L->getExitingBlock() &&
226 "Exiting Blocks is out of sync");
227 assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
228 assert(Latch == L->getLoopLatch() && "Latch is out of sync");
229 }
230
231 /// Get the entry block for this fusion candidate.
232 ///
233 /// If this fusion candidate represents a guarded loop, the entry block is the
234 /// loop guard block. If it represents an unguarded loop, the entry block is
235 /// the preheader of the loop.
236 BasicBlock *getEntryBlock() const {
237 if (GuardBranch)
238 return GuardBranch->getParent();
239 return Preheader;
240 }
241
242 /// After Peeling the loop is modified quite a bit, hence all of the Blocks
243 /// need to be updated accordingly.
244 void updateAfterPeeling() {
245 Preheader = L->getLoopPreheader();
246 Header = L->getHeader();
247 ExitingBlock = L->getExitingBlock();
248 ExitBlock = L->getExitBlock();
249 Latch = L->getLoopLatch();
250 verify();
251 }
252
253 /// Given a guarded loop, get the successor of the guard that is not in the
254 /// loop.
255 ///
256 /// This method returns the successor of the loop guard that is not located
257 /// within the loop (i.e., the successor of the guard that is not the
258 /// preheader).
259 /// This method is only valid for guarded loops.
260 BasicBlock *getNonLoopBlock() const {
261 assert(GuardBranch && "Only valid on guarded loops.");
262 if (Peeled)
263 return GuardBranch->getSuccessor(1);
264 return (GuardBranch->getSuccessor(0) == Preheader)
265 ? GuardBranch->getSuccessor(1)
266 : GuardBranch->getSuccessor(0);
267 }
268
269#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
270 LLVM_DUMP_METHOD void dump() const {
271 dbgs() << "\tGuardBranch: ";
272 if (GuardBranch)
273 dbgs() << *GuardBranch;
274 else
275 dbgs() << "nullptr";
276 dbgs() << "\n"
277 << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
278 << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
279 << "\n"
280 << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
281 << "\tExitingBB: "
282 << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
283 << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
284 << "\n"
285 << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
286 << "\tEntryBlock: "
287 << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
288 << "\n";
289 }
290#endif
291
292 /// Determine if a fusion candidate (representing a loop) is eligible for
293 /// fusion. Note that this only checks whether a single loop can be fused - it
294 /// does not check whether it is *legal* to fuse two loops together.
295 bool isEligibleForFusion(ScalarEvolution &SE) const {
296 if (!isValid()) {
297 LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
298 assert(Header && "Header should be guaranteed to exist!");
299 ++InvalidLoopStructure;
300 return false;
301 }
302
303 // Require ScalarEvolution to be able to determine a trip count.
305 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
306 << " trip count not computable!\n");
307 ++UnknownTripCount;
308 return reportInvalidCandidate("UnknownTripCount",
309 "Loop has unknown trip count");
310 }
311
312 if (!L->isLoopSimplifyForm()) {
313 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
314 << " is not in simplified form!\n");
315 ++NotSimplifiedForm;
316 return reportInvalidCandidate("NotSimplifiedForm",
317 "Loop is not in simplified form");
318 }
319
320 if (!L->isRotatedForm()) {
321 LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
322 ++NotRotated;
323 return reportInvalidCandidate("NotRotated", "Candidate is not rotated");
324 }
325
326 return true;
327 }
328
329private:
330 // This is only used internally for now, to clear the MemWrites and MemReads
331 // list and setting Valid to false. I can't envision other uses of this right
332 // now, since once FusionCandidates are put into the FusionCandidateList they
333 // are immutable. Thus, any time we need to change/update a FusionCandidate,
334 // we must create a new one and insert it into the FusionCandidateList to
335 // ensure the FusionCandidateList remains ordered correctly.
336 void invalidate() {
337 MemWrites.clear();
338 MemReads.clear();
339 Valid = false;
340 }
341
342 // Emit an analysis remark explaining why this loop cannot be fused. The
343 // remark is built from explicit strings so it does not depend on whether
344 // statistics are enabled. \p RemarkName is the -Rpass remark identifier and
345 // \p RemarkMsg the human-readable reason.
346 bool reportInvalidCandidate(StringRef RemarkName, StringRef RemarkMsg) const {
347 using namespace ore;
348 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "InvalidCandidate",
349 L->getStartLoc(), L->getHeader())
350 << "Loop is not a candidate for fusion");
351
353 L->getStartLoc(), L->getHeader())
354 << "[" << L->getHeader()->getParent()->getName() << "]: "
355 << "Loop is not a candidate for fusion: " << RemarkMsg);
356 return false;
357 }
358};
359} // namespace
360
362
363// List of adjacent fusion candidates in order. Thus, if FC0 comes *before* FC1
364// in a FusionCandidateList, then FC0 dominates FC1, FC1 post-dominates FC0,
365// and they are adjacent.
366using FusionCandidateList = std::list<FusionCandidate>;
368
369#ifndef NDEBUG
370static void printLoopVector(const LoopVector &LV) {
371 dbgs() << "****************************\n";
372 for (const Loop *L : LV)
373 printLoop(*L, dbgs());
374 dbgs() << "****************************\n";
375}
376
377static raw_ostream &operator<<(raw_ostream &OS, const FusionCandidate &FC) {
378 if (FC.isValid())
379 OS << FC.Preheader->getName();
380 else
381 OS << "<Invalid>";
382
383 return OS;
384}
385
387 const FusionCandidateList &CandList) {
388 for (const FusionCandidate &FC : CandList)
389 OS << FC << '\n';
390
391 return OS;
392}
393
394static void
396 dbgs() << "Fusion Candidates: \n";
397 for (const auto &CandidateList : FusionCandidates) {
398 dbgs() << "*** Fusion Candidate List ***\n";
399 dbgs() << CandidateList;
400 dbgs() << "****************************\n";
401 }
402}
403#endif // NDEBUG
404
405/// Fold away an empty block on the "skip" edge of \p L's loop guard, if any.
406///
407/// Loop::getLoopGuardBranch() recognizes a guard only when the non-loop
408/// successor of the guard branch is the block that the loop exit flows into
409/// (looking through empty blocks on the exit side only). Passes such as
410/// JumpThreading can leave an empty forwarding block on the guard side
411/// instead:
412///
413/// Guard: br %c, %Preheader, %Skip
414/// Skip: br %Merge ; empty, only reachable from Guard
415/// ...
416/// Exit: br %Merge
417/// Merge: ...
418///
419/// which makes getLoopGuardBranch() treat \p L as unguarded.
420/// This function folds %Skip: it redirects the guard branch to %Merge and
421/// deletes the empty %Skip block. Loop fusion calls this on every loop before
422/// collecting fusion candidates so that a guarded loop left in this shape by
423/// an earlier pass is still recognized as guarded and as adjacent to its
424/// neighbor. Returns true if the CFG was changed.
426 ScalarEvolution &SE) {
427 if (!L->isLoopSimplifyForm() || !L->isRotatedForm())
428 return false;
429
430 BasicBlock *Preheader = L->getLoopPreheader();
431 BasicBlock *ExitBlock = L->getUniqueExitBlock();
432 if (!ExitBlock)
433 return false;
434
435 BasicBlock *GuardBB = Preheader->getUniquePredecessor();
436 if (!GuardBB)
437 return false;
438
439 auto *GuardBI = dyn_cast<CondBrInst>(GuardBB->getTerminator());
440 if (!GuardBI)
441 return false;
442
443 BasicBlock *SkipBB = GuardBI->getSuccessor(0) == Preheader
444 ? GuardBI->getSuccessor(1)
445 : GuardBI->getSuccessor(0);
446 if (SkipBB == Preheader)
447 return false;
448
449 // The skip block must contain nothing but an unconditional branch and must
450 // be reachable only from the guard, so that removing it cannot change any
451 // other path.
452 if (SkipBB->size() != 1 || !isa<UncondBrInst>(SkipBB->getTerminator()) ||
453 SkipBB->hasAddressTaken() || SkipBB->getUniquePredecessor() != GuardBB)
454 return false;
455
456 BasicBlock *MergeBB = SkipBB->getUniqueSuccessor();
457 if (!MergeBB || MergeBB == SkipBB || MergeBB == GuardBB ||
458 LI.isLoopHeader(MergeBB))
459 return false;
460
461 // The loop exit must flow into the same block; otherwise the branch is
462 // not a loop guard.
463 if (&LoopNest::skipEmptyBlockUntil(ExitBlock, MergeBB,
464 /*CheckUniquePred=*/true) != MergeBB)
465 return false;
466
467 LLVM_DEBUG(dbgs() << "Removing empty guard skip block " << SkipBB->getName()
468 << " of loop " << L->getHeader()->getName() << "\n");
469
470 MergeBB->replacePhiUsesWith(SkipBB, GuardBB);
471 GuardBI->replaceSuccessorWith(SkipBB, MergeBB);
472 SkipBB->getTerminator()->eraseFromParent();
473 new UnreachableInst(SkipBB->getContext(), SkipBB);
474
475 DTU.applyUpdates({{DominatorTree::Delete, GuardBB, SkipBB},
476 {DominatorTree::Delete, SkipBB, MergeBB},
477 {DominatorTree::Insert, GuardBB, MergeBB}});
478 LI.removeBlock(SkipBB);
479 DTU.deleteBB(SkipBB);
480 DTU.flush();
481
482 return true;
483}
484
485namespace {
486
487/// Collect all loops in function at the same nest level, starting at the
488/// outermost level.
489///
490/// This data structure collects all loops at the same nest level for a
491/// given function (specified by the LoopInfo object). It starts at the
492/// outermost level.
493struct LoopDepthTree {
494 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
495 using iterator = LoopsOnLevelTy::iterator;
496 using const_iterator = LoopsOnLevelTy::const_iterator;
497
498 LoopDepthTree(LoopInfo &LI) : Depth(1) {
499 if (!LI.empty())
500 LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
501 }
502
503 /// Test whether a given loop has been removed from the function, and thus is
504 /// no longer valid.
505 bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
506
507 /// Record that a given loop has been removed from the function and is no
508 /// longer valid.
509 void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
510
511 /// Descend the tree to the next (inner) nesting level
512 void descend() {
513 LoopsOnLevelTy LoopsOnNextLevel;
514
515 for (const LoopVector &LV : *this)
516 for (Loop *L : LV)
517 if (!isRemovedLoop(L) && L->begin() != L->end())
518 LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
519
520 LoopsOnLevel = LoopsOnNextLevel;
521 RemovedLoops.clear();
522 Depth++;
523 }
524
525 bool empty() const { return size() == 0; }
526 size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
527 unsigned getDepth() const { return Depth; }
528
529 iterator begin() { return LoopsOnLevel.begin(); }
530 iterator end() { return LoopsOnLevel.end(); }
531 const_iterator begin() const { return LoopsOnLevel.begin(); }
532 const_iterator end() const { return LoopsOnLevel.end(); }
533
534private:
535 /// Set of loops that have been removed from the function and are no longer
536 /// valid.
537 SmallPtrSet<const Loop *, 8> RemovedLoops;
538
539 /// Depth of the current level, starting at 1 (outermost loops).
540 unsigned Depth;
541
542 /// Vector of loops at the current depth level that have the same parent loop
543 LoopsOnLevelTy LoopsOnLevel;
544};
545
546struct LoopFuser {
547private:
548 const ScalarOptions &Opts;
549
550 // Sets of control flow equivalent fusion candidates for a given nest level.
551 FusionCandidateCollection FusionCandidates;
552
553 LoopDepthTree LDT;
554 DomTreeUpdater DTU;
555
556 LoopInfo &LI;
557 DominatorTree &DT;
558 DependenceInfo &DI;
559 AAResults &AA;
560 ScalarEvolution &SE;
561 PostDominatorTree &PDT;
562 OptimizationRemarkEmitter &ORE;
563 AssumptionCache &AC;
564 const TargetTransformInfo &TTI;
565
566public:
567 LoopFuser(const ScalarOptions &Opts, LoopInfo &LI, DominatorTree &DT,
568 DependenceInfo &DI, AAResults &AA, ScalarEvolution &SE,
569 PostDominatorTree &PDT, OptimizationRemarkEmitter &ORE,
570 AssumptionCache &AC, const TargetTransformInfo &TTI)
571 : Opts(Opts), LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy),
572 LI(LI), DT(DT), DI(DI), AA(AA), SE(SE), PDT(PDT), ORE(ORE), AC(AC),
573 TTI(TTI) {}
574
575 /// This is the main entry point for loop fusion. It will traverse the
576 /// specified function and collect candidate loops to fuse, starting at the
577 /// outermost nesting level and working inwards.
578 bool fuseLoops(Function &F) {
579#ifndef NDEBUG
580 if (Opts.loop_fusion_verbose_debug) {
581 LI.print(dbgs());
582 }
583#endif
584
585 LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
586 << "\n");
587 bool Changed = false;
588
589 while (!LDT.empty()) {
590 LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
591 << LDT.getDepth() << "\n";);
592
593 for (const LoopVector &LV : LDT) {
594 assert(LV.size() > 0 && "Empty loop set was build!");
595
596 // Skip singleton loop sets as they do not offer fusion opportunities on
597 // this level.
598 if (LV.size() == 1)
599 continue;
600#ifndef NDEBUG
601 if (Opts.loop_fusion_verbose_debug) {
602 LLVM_DEBUG({
603 dbgs() << " Visit loop set (#" << LV.size() << "):\n";
604 printLoopVector(LV);
605 });
606 }
607#endif
608
609 collectFusionCandidates(LV);
610 Changed |= fuseCandidates();
611 // All loops in the candidate sets have a common parent (or no parent).
612 // Next loop vector will correspond to a different parent. It is safe
613 // to remove all the candidates currently in the set.
614 FusionCandidates.clear();
615 }
616
617 // Finished analyzing candidates at this level. Descend to the next level.
618 LLVM_DEBUG(dbgs() << "Descend one level!\n");
619 LDT.descend();
620 }
621
622 if (Changed)
623 LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
624
625#ifndef NDEBUG
626 assert(DT.verify());
627 assert(PDT.verify());
628 LI.verify();
629 SE.verify();
630#endif
631
632 LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
633 return Changed;
634 }
635
636private:
637 /// Iterate over all loops in the given loop set and identify the loops that
638 /// are eligible for fusion. Place all eligible fusion candidates into Control
639 /// Flow Equivalent sets, sorted by dominance.
640 void collectFusionCandidates(const LoopVector &LV) {
641 for (Loop *L : LV) {
643 gatherPeelingPreferences(L, SE, TTI, std::nullopt, std::nullopt);
644 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
645 if (!CurrCand.isEligibleForFusion(SE))
646 continue;
647
648 // Go through each list in FusionCandidates and determine if the first or
649 // last loop in the list is strictly adjacent to L. If it is, append L.
650 // If not, go to the next list.
651 // If no suitable list is found, start another list and add it to
652 // FusionCandidates.
653 bool FoundAdjacent = false;
654 for (auto &CurrCandList : FusionCandidates) {
655 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
656 CurrCandList.push_back(CurrCand);
657 FoundAdjacent = true;
658 NumFusionCandidates++;
659#ifndef NDEBUG
660 if (Opts.loop_fusion_verbose_debug)
661 LLVM_DEBUG(dbgs() << "Adding " << CurrCand
662 << " to existing candidate list\n");
663#endif
664 break;
665 }
666 }
667 if (!FoundAdjacent) {
668 // No list was found. Create a new list and add to FusionCandidates
669#ifndef NDEBUG
670 if (Opts.loop_fusion_verbose_debug)
671 LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new list\n");
672#endif
673 FusionCandidateList NewCandList;
674 NewCandList.push_back(CurrCand);
675 FusionCandidates.push_back(NewCandList);
676 }
677 }
678 }
679
680 /// Determine if it is beneficial to fuse two loops.
681 bool isBeneficialFusion(unsigned ReusedValueCount) const {
682 if (Opts.loop_fusion_disable_cost_model)
683 return true;
684 return ReusedValueCount >= Opts.loop_fusion_min_reused_values;
685 }
686
687 /// Computes the integer difference in trip counts:
688 /// TripCount(FC0) - TripCount(FC1).
689 ///
690 /// \returns The integer difference, or std::nullopt if it
691 /// cannot be determined.
692 std::optional<int64_t>
693 calculateTripCountDiff(const FusionCandidate &FC0,
694 const FusionCandidate &FC1) const {
695 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
696 if (isa<SCEVCouldNotCompute>(TripCount0)) {
697 UncomputableTripCount++;
698 LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
699 return std::nullopt;
700 }
701
702 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
703 if (isa<SCEVCouldNotCompute>(TripCount1)) {
704 UncomputableTripCount++;
705 LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
706 return std::nullopt;
707 }
708
709 LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
710 << *TripCount1 << " are "
711 << (TripCount0 == TripCount1 ? "identical" : "different")
712 << "\n");
713
714 if (TripCount0 == TripCount1)
715 return 0;
716
717 LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
718 "determining the difference between trip counts\n");
719
720 // Currently only considering loops with a single exit point
721 // and a non-constant trip count. Note that the return value
722 // of getSmallConstantTripCount is a 32 bit number, based on
723 // the existing implementation.
724 const int64_t TC0 =
725 static_cast<int64_t>(SE.getSmallConstantTripCount(FC0.L));
726 const int64_t TC1 =
727 static_cast<int64_t>(SE.getSmallConstantTripCount(FC1.L));
728
729 // If any of the tripcounts are zero that means that loop(s) do not have
730 // a single exit or a constant tripcount.
731 if (TC0 == 0 || TC1 == 0) {
732 LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
733 "have a constant number of iterations. Peeling "
734 "is not benefical\n");
735 return std::nullopt;
736 }
737
738 return TC0 - TC1;
739 }
740
741 void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
742 unsigned PeelCount) {
743 assert(FC0.AbleToPeel && "Should be able to peel loop");
744
745 LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
746 << " iterations of the first loop. \n");
747
749 // LoopFusion is a function pass that neither requires nor preserves
750 // LCSSA, so peelLoop need not preserve it across its internal
751 // simplifyLoop call.
752 peelLoop(FC0.L, PeelCount, /*PeelLast=*/false, &LI, &SE, DT, &AC,
753 /*PreserveLCSSA=*/false, VMap);
754 FC0.Peeled = true;
755 LLVM_DEBUG(dbgs() << "Done Peeling\n");
756
757#ifndef NDEBUG
758 auto TCDiff = calculateTripCountDiff(FC0, FC1);
759
760 assert(TCDiff && *TCDiff == 0 &&
761 "Loops should have identical trip counts after peeling");
762#endif
763
764 FC0.PP.PeelCount += PeelCount;
765
766 // Peeling does not update the PDT
767 PDT.recalculate(*FC0.Preheader->getParent());
768
769 FC0.updateAfterPeeling();
770
771 // In this case the iterations of the loop are constant, so the first
772 // loop will execute completely (will not jump from one of
773 // the peeled blocks to the second loop). Here we are updating the
774 // branch conditions of each of the peeled blocks, such that it will
775 // branch to its successor which is not the preheader of the second loop
776 // in the case of unguarded loops, or the succesors of the exit block of
777 // the first loop otherwise. Doing this update will ensure that the entry
778 // block of the first loop dominates the entry block of the second loop.
779 BasicBlock *BB =
780 FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
781 if (BB) {
783 SmallVector<Instruction *, 8> WorkList;
784 for (BasicBlock *Pred : predecessors(BB)) {
785 if (Pred != FC0.ExitBlock) {
786 WorkList.emplace_back(Pred->getTerminator());
787 TreeUpdates.emplace_back(
788 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
789 }
790 }
791 // Cannot modify the predecessors inside the above loop as it will cause
792 // the iterators to be nullptrs, causing memory errors.
793 for (Instruction *CurrentBranch : WorkList) {
794 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
795 if (Succ == BB)
796 Succ = CurrentBranch->getSuccessor(1);
797 ReplaceInstWithInst(CurrentBranch, UncondBrInst::Create(Succ));
798 }
799
800 DTU.applyUpdates(TreeUpdates);
801 DTU.flush();
802 }
804 dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
805 << " iterations from the first loop.\n"
806 "Both Loops have the same number of iterations now.\n");
807 }
808
809 /// Walk each set of strictly adjacent fusion candidates and attempt to fuse
810 /// them. This does a single linear traversal of all candidates in the list.
811 /// The conditions for legal fusion are checked at this point. If a pair of
812 /// fusion candidates passes all legality checks, they are fused together and
813 /// a new fusion candidate is created and added to the FusionCandidateList.
814 /// The original fusion candidates are then removed, as they are no longer
815 /// valid.
816 bool fuseCandidates() {
817 bool Fused = false;
818 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
819 for (auto &CandidateList : FusionCandidates) {
820 if (CandidateList.size() < 2)
821 continue;
822
823 LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate List:\n"
824 << CandidateList << "\n");
825
826 for (auto It = CandidateList.begin(), NextIt = std::next(It);
827 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
828
829 const FusionCandidate &FC0 = *It;
830 const FusionCandidate &FC1 = *NextIt;
831
832 assert(!LDT.isRemovedLoop(FC0.L) &&
833 "Should not have removed loops in CandidateList!");
834 assert(!LDT.isRemovedLoop(FC1.L) &&
835 "Should not have removed loops in CandidateList!");
836
837 LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0.dump();
838 dbgs() << " with\n"; FC1.dump(); dbgs() << "\n");
839
840 FC0.verify();
841 FC1.verify();
842
843 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
844 // Here we are checking that FC0 (the first loop) can be peeled, and
845 // the first loop has a larger trip count. In this case it is possible
846 // that the first loop is peeled to expose the fusion opportunity.
847 // Peeling the second loop is not currently supported.
848 bool WillPeel = FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
849 *TCDifference <= static_cast<int64_t>(
850 Opts.loop_fusion_peel_max_count);
851
852 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
853 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
854 "counts and peeling is not supported for this "
855 "case. Not fusing.\n");
856 ++NonEqualTripCount;
857 reportLoopFusion<OptimizationRemarkMissed>(
858 FC0, FC1, "NonEqualTripCount",
859 "Loop trip counts are not the same");
860 continue;
861 }
862
863 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
864 (FC0.GuardBranch && !FC1.GuardBranch)) {
865 LLVM_DEBUG(dbgs() << "The one of candidate is guarded while the "
866 "another one is not. Not fusing.\n");
867 ++OnlySecondCandidateIsGuarded;
868 reportLoopFusion<OptimizationRemarkMissed>(
869 FC0, FC1, "OnlySecondCandidateIsGuarded",
870 "The second candidate is guarded while the first one is not");
871 continue;
872 }
873
874 // If Loops are guarded, we expect the guards to be identical.
875 // Currently peeling is supported only for loops with constant
876 // iteration counts. If two loops have different loop guards
877 // there is no mechanism in loop fusion to make their fusion legal.
878 // The trivial case where the guards compare two constant values can be
879 // ignored. Those guards will be optimized away by other passes.
880 if (FC0.GuardBranch && FC1.GuardBranch &&
881 !haveIdenticalGuards(FC0, FC1)) {
882 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
883 "guards. Not Fusing.\n");
884 ++NonIdenticalGuards;
885 reportLoopFusion<OptimizationRemarkMissed>(
886 FC0, FC1, "NonIdenticalGuards",
887 "Candidates have different guards");
888 continue;
889 }
890
891 if (FC0.GuardBranch) {
892 assert(FC1.GuardBranch && "Expecting valid FC1 guard branch");
893
894 if (!isSafeToMoveBefore(*FC0.ExitBlock,
895 *FC1.ExitBlock->getFirstNonPHIOrDbg(), DT,
896 &PDT, &DI)) {
897 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
898 "instructions in exit block. Not fusing.\n");
899 ++NonEmptyExitBlock;
900 reportLoopFusion<OptimizationRemarkMissed>(
901 FC0, FC1, "NonEmptyExitBlock",
902 "Candidate has a non-empty exit block with "
903 "instructions that cannot be moved");
904 continue;
905 }
906
908 *FC1.GuardBranch->getParent(),
909 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
910 &DI)) {
911 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
912 "instructions in guard block. Not fusing.\n");
913 ++NonEmptyGuardBlock;
914 reportLoopFusion<OptimizationRemarkMissed>(
915 FC0, FC1, "NonEmptyGuardBlock",
916 "Candidate has a non-empty guard block with "
917 "instructions that cannot be moved");
918 continue;
919 }
920 }
921
922 // Check the dependencies across the loops and do not fuse if it would
923 // violate them.
924 ReusedValueSet ReusedValues;
925 if (!dependencesAllowFusion(FC0, FC1, &ReusedValues)) {
926 LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
927 ++InvalidDependencies;
928 reportLoopFusion<OptimizationRemarkMissed>(
929 FC0, FC1, "InvalidDependencies", "Dependencies prevent fusion");
930 continue;
931 }
932
933 // If the second loop has instructions in the pre-header, attempt to
934 // hoist them up to the first loop's pre-header or sink them into the
935 // body of the second loop.
936 SmallVector<Instruction *, 4> SafeToHoist;
937 SmallVector<Instruction *, 4> SafeToSink;
938 // At this point, this is the last remaining legality check.
939 // Which means if we can make this pre-header empty, we can fuse
940 // these loops
941 if (!isEmptyPreheader(FC1)) {
942 LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
943 "preheader.\n");
944
945 // If it is not safe to hoist/sink all instructions in the
946 // pre-header, we cannot fuse these loops.
947 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
948 SafeToSink)) {
949 LLVM_DEBUG(dbgs() << "Could not hoist/sink all instructions in "
950 "Fusion Candidate Pre-header.\n"
951 << "Not Fusing.\n");
952 ++NonEmptyPreheader;
953 reportLoopFusion<OptimizationRemarkMissed>(
954 FC0, FC1, "NonEmptyPreheader",
955 "Loop has a non-empty preheader with instructions that "
956 "cannot be moved");
957 continue;
958 }
959 }
960
961 unsigned ReusedValueCount = ReusedValues.size();
962 bool BeneficialToFuse = isBeneficialFusion(ReusedValueCount);
963 LLVM_DEBUG(dbgs() << "\tFusion appears to be "
964 << (BeneficialToFuse ? "" : "un") << "profitable!\n");
965 if (!BeneficialToFuse) {
966 ++InsufficientReuse;
967 reportFusionInsufficientReuse(FC0, FC1, ReusedValueCount);
968 continue;
969 }
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 using AffineLoadKey = std::tuple<const SCEV *, const SCEV *>;
1187
1188 std::optional<AffineLoadKey> getAffineLoadKey(const FusionCandidate &FC,
1189 Instruction &I) {
1190 auto *Load = dyn_cast<LoadInst>(&I);
1191 if (!Load)
1192 return std::nullopt;
1193
1194 const auto *AR =
1195 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Load->getPointerOperand()));
1196 if (!AR || AR->getLoop() != FC.L || !AR->isAffine())
1197 return std::nullopt;
1198
1199 return AffineLoadKey{AR->getStart(), AR->getStepRecurrence(SE)};
1200 }
1201
1202 /// Return true if \p A is known to execute before \p B in an iteration of
1203 /// \p L. Keep accesses in nested loops conservative.
1204 bool isKnownBefore(const Instruction *A, const Instruction *B,
1205 const Loop *L) const {
1206 return LI.getLoopFor(A->getParent()) == L &&
1207 LI.getLoopFor(B->getParent()) == L && DT.dominates(A, B);
1208 }
1209
1210 /// Return true if a write between the corresponding loads may overwrite
1211 /// either loaded memory location.
1212 bool hasInterveningWrite(BatchAAResults &BAA, const LoadInst &Load0,
1213 const LoadInst &Load1, const FusionCandidate &FC0,
1214 const FusionCandidate &FC1) const {
1215 MemoryLocation Loc0 = MemoryLocation::get(&Load0);
1216 MemoryLocation Loc1 = MemoryLocation::get(&Load1);
1217 auto MayModify = [&](Instruction *Write) {
1218 return isModSet(BAA.getModRefInfo(Write, Loc0)) ||
1219 isModSet(BAA.getModRefInfo(Write, Loc1));
1220 };
1221
1222 for (Instruction *Write : FC0.MemWrites)
1223 if (!isKnownBefore(Write, &Load0, FC0.L) && MayModify(Write))
1224 return true;
1225 for (Instruction *Write : FC1.MemWrites)
1226 if (!isKnownBefore(&Load1, Write, FC1.L) && MayModify(Write))
1227 return true;
1228 return false;
1229 }
1230
1231 /// Collect distinct read-read addresses reused at corresponding iterations.
1232 ///
1233 /// This uses exact affine SCEV equality rather than adding a potentially
1234 /// expensive read-read DependenceAnalysis query for every load pair.
1235 void collectReadReadReuse(const FusionCandidate &FC0,
1236 const FusionCandidate &FC1,
1237 ReusedValueSet &ReusedValues) {
1238 if (ReusedValues.size() >= Opts.loop_fusion_min_reused_values)
1239 return;
1240
1241 BatchAAResults BAA(AA);
1242 SmallDenseMap<AffineLoadKey, Instruction *, 8> LoadAccesses0;
1243 for (Instruction *ReadL0 : FC0.MemReads) {
1244 std::optional<AffineLoadKey> Key = getAffineLoadKey(FC0, *ReadL0);
1245 if (!Key)
1246 continue;
1247
1248 LoadAccesses0.try_emplace(*Key, ReadL0);
1249 }
1250
1251 for (Instruction *ReadL1 : FC1.MemReads) {
1252 std::optional<AffineLoadKey> Key = getAffineLoadKey(FC1, *ReadL1);
1253 if (!Key)
1254 continue;
1255
1256 Instruction *MatchingLoad = LoadAccesses0.lookup(*Key);
1257 if (!MatchingLoad)
1258 continue;
1259
1260 auto *Load0 = cast<LoadInst>(MatchingLoad);
1261 auto *Load1 = cast<LoadInst>(ReadL1);
1262 if (hasInterveningWrite(BAA, *Load0, *Load1, FC0, FC1))
1263 continue;
1264
1265 ReusedValues.insert(MatchingLoad);
1266 LLVM_DEBUG(dbgs() << "Same-iteration read-read reuse via "
1267 << *MatchingLoad << "\n");
1268 if (ReusedValues.size() >= Opts.loop_fusion_min_reused_values)
1269 return;
1270 }
1271 }
1272
1273 /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
1274 /// @p L1) allow loop fusion of @p L0 and @p L1.
1275 bool dependencesAllowFusion(const FusionCandidate &FC0,
1276 const FusionCandidate &FC1, Instruction &I0,
1277 Instruction &I1,
1278 ReusedValueSet *ReusedValues = nullptr) {
1279#ifndef NDEBUG
1280 if (Opts.loop_fusion_verbose_debug) {
1281 LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << "\n");
1282 }
1283#endif
1284 auto DepResult = DI.depends(&I0, &I1);
1285 if (!DepResult)
1286 return true;
1287 // If two stores write the same SSA value, fusion is safe regardless of
1288 // aliasing - writing the same value twice is idempotent.
1289 if (isa<StoreInst>(I0) && isa<StoreInst>(I1)) {
1290 auto *S0 = cast<StoreInst>(&I0);
1291 auto *S1 = cast<StoreInst>(&I1);
1292 if (S0->getValueOperand() == S1->getValueOperand())
1293 return true;
1294 }
1295#ifndef NDEBUG
1296 if (Opts.loop_fusion_verbose_debug) {
1297 LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
1298 dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
1299 << (DepResult->isOrdered() ? "true" : "false")
1300 << "]\n");
1301 LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
1302 << "\n");
1303 }
1304#endif
1305 unsigned Levels = DepResult->getLevels();
1306 unsigned SameSDLevels = DepResult->getSameSDLevels();
1307 unsigned CurLoopLevel = FC0.L->getLoopDepth();
1308
1309 // Check if DA is missing info regarding the current loop level
1310 if (CurLoopLevel > Levels + SameSDLevels)
1311 return false;
1312
1313 // Iterating over the outer levels.
1314 for (unsigned Level = 1; Level <= std::min(CurLoopLevel - 1, Levels);
1315 ++Level) {
1316 unsigned Direction = DepResult->getDirection(Level, false);
1317
1318 // Check if the direction vector does not include equality. If an outer
1319 // loop has a non-equal direction, outer indicies are different and it
1320 // is safe to fuse.
1322 LLVM_DEBUG(dbgs() << "Safe to fuse due to non-equal acceses in the "
1323 "outer loops\n");
1324 NumDA++;
1325 return true;
1326 }
1327 }
1328
1329 assert(CurLoopLevel > Levels && "Fusion candidates are not separated");
1330
1331 unsigned CurDir = DepResult->getDirection(CurLoopLevel, true);
1332
1333 if (ReusedValues && !DepResult->isConfused() && DepResult->isFlow() &&
1334 CurDir == Dependence::DVEntry::EQ) {
1335 ReusedValues->insert(&I0);
1336 LLVM_DEBUG(dbgs() << "Same-iteration reuse via " << I0 << "\n");
1337 }
1338
1339 if (DepResult->isScalar(CurLoopLevel, true)) {
1340 if (DepResult->isInput() || DepResult->isOutput()) {
1341 LLVM_DEBUG(dbgs() << "Safe to fuse due to a loop-invariant "
1342 << (DepResult->isInput() ? "input" : "output")
1343 << " dependency\n");
1344 NumDA++;
1345 return true;
1346 }
1347 // Same-iteration scalar flow/anti dependences between adjacent loops are
1348 // preserved by placing FC0's body before FC1's body in the fused loop.
1349 // This enables fusing accumulation chains such as:
1350 // for (i)
1351 // A[i] = ...;
1352 // for (i)
1353 // A[i] += ...;
1354 if (!(CurDir & Dependence::DVEntry::GT) &&
1355 !(CurDir & Dependence::DVEntry::LT)) {
1356 LLVM_DEBUG(dbgs() << "Safe to fuse same-iteration scalar dependence\n");
1357 NumDA++;
1358 return true;
1359 }
1360 LLVM_DEBUG(
1361 dbgs() << "Not safe to fuse due to a scalar flow dependency\n");
1362 return false;
1363 }
1364
1365 // Check if the direction vector does not include greater direction. In
1366 // that case, the dependency is not a backward loop-carried and is legal
1367 // to fuse. For example here we have a forward dependency
1368 // for (int i = 0; i < n; i++)
1369 // A[i] = ...;
1370 // for (int i = 0; i < n; i++)
1371 // ... = A[i-1];
1372 if (!(CurDir & Dependence::DVEntry::GT)) {
1373 LLVM_DEBUG(dbgs() << "Safe to fuse with no backward loop-carried "
1374 "dependency\n");
1375 NumDA++;
1376 return true;
1377 }
1378
1379 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1380 LLVM_DEBUG(dbgs() << "TODO: Implement pred/succ dependence handling!\n");
1381
1382 return false;
1383 }
1384
1385 /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
1386 bool dependencesAllowFusion(const FusionCandidate &FC0,
1387 const FusionCandidate &FC1,
1388 ReusedValueSet *ReusedValues) {
1389 LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
1390 << "\n");
1391 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
1392 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1393
1394 // Walk through all uses in FC1. For each use, find the reaching def.
1395 // If the def is located in FC0 then it is not safe to fuse.
1396 for (BasicBlock *BB : FC1.L->blocks())
1397 for (Instruction &I : *BB)
1398 for (auto &Op : I.operands())
1399 if (Instruction *Def = dyn_cast<Instruction>(Op))
1400 if (FC0.L->contains(Def->getParent())) {
1401 return false;
1402 }
1403
1404 for (Instruction *WriteL0 : FC0.MemWrites) {
1405 for (Instruction *WriteL1 : FC1.MemWrites)
1406 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1407 return false;
1408 }
1409 for (Instruction *ReadL1 : FC1.MemReads)
1410 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
1411 ReusedValues)) {
1412 return false;
1413 }
1414 }
1415
1416 // Write-write and write-read pairs are already covered above; only the
1417 // read-before-write pairs from FC0 reads to FC1 writes remain.
1418 for (Instruction *ReadL0 : FC0.MemReads)
1419 for (Instruction *WriteL1 : FC1.MemWrites)
1420 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1421 return false;
1422 }
1423
1424 if (ReusedValues && !Opts.loop_fusion_disable_cost_model)
1425 collectReadReadReuse(FC0, FC1, *ReusedValues);
1426
1427 return true;
1428 }
1429
1430 /// Determine if two fusion candidates are strictly adjacent in the CFG.
1431 ///
1432 /// This method will determine if there are additional basic blocks in the CFG
1433 /// between the exit of \p FC0 and the entry of \p FC1.
1434 /// If the two candidates are guarded loops, then it checks whether the
1435 /// exit block of the \p FC0 is the predecessor of the \p FC1 preheader. This
1436 /// implicitly ensures that the non-loop successor of the \p FC0 guard branch
1437 /// is the entry block of \p FC1. If not, then the loops are not adjacent. If
1438 /// the two candidates are not guarded loops, then it checks whether the exit
1439 /// block of \p FC0 is the preheader of \p FC1.
1440 /// Strictly means there is no predecessor for FC1 unless it is from FC0,
1441 /// i.e., FC0 dominates FC1.
1442 bool isStrictlyAdjacent(const FusionCandidate &FC0,
1443 const FusionCandidate &FC1) const {
1444 // If the successor of the guard branch is FC1, then the loops are adjacent
1445 if (FC0.GuardBranch)
1446 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1447 FC0.ExitBlock->getSingleSuccessor() == FC1.getEntryBlock();
1448 return FC0.ExitBlock == FC1.getEntryBlock();
1449 }
1450
1451 bool isEmptyPreheader(const FusionCandidate &FC) const {
1452 return FC.Preheader->size() == 1;
1453 }
1454
1455 /// Hoist \p FC1 Preheader instructions to \p FC0 Preheader
1456 /// and sink others into the body of \p FC1.
1457 void movePreheaderInsts(const FusionCandidate &FC0,
1458 const FusionCandidate &FC1,
1459 SmallVector<Instruction *, 4> &HoistInsts,
1460 SmallVector<Instruction *, 4> &SinkInsts) const {
1461 // All preheader instructions except the branch must be hoisted or sunk
1462 assert(HoistInsts.size() + SinkInsts.size() == FC1.Preheader->size() - 1 &&
1463 "Attempting to sink and hoist preheader instructions, but not all "
1464 "the preheader instructions are accounted for.");
1465
1466 NumHoistedInsts += HoistInsts.size();
1467 NumSunkInsts += SinkInsts.size();
1468
1469 LLVM_DEBUG(if (Opts.loop_fusion_verbose_debug) {
1470 if (!HoistInsts.empty())
1471 dbgs() << "Hoisting: \n";
1472 for (Instruction *I : HoistInsts)
1473 dbgs() << *I << "\n";
1474 if (!SinkInsts.empty())
1475 dbgs() << "Sinking: \n";
1476 for (Instruction *I : SinkInsts)
1477 dbgs() << *I << "\n";
1478 });
1479
1480 for (Instruction *I : HoistInsts) {
1481 assert(I->getParent() == FC1.Preheader);
1482 I->moveBefore(*FC0.Preheader,
1483 FC0.Preheader->getTerminator()->getIterator());
1484 }
1485 // insert instructions in reverse order to maintain dominance relationship
1486 for (Instruction *I : reverse(SinkInsts)) {
1487 assert(I->getParent() == FC1.Preheader);
1488 if (isa<PHINode>(I)) {
1489 // The Phis to be sunk should have only one incoming value, as is
1490 // assured by the condition that the second loop is dominated by the
1491 // first one which is enforced by isStrictlyAdjacent().
1492 // Replace the phi uses with the corresponding incoming value to clean
1493 // up the code.
1494 assert(cast<PHINode>(I)->getNumIncomingValues() == 1 &&
1495 "Expected the sunk PHI node to have 1 incoming value.");
1496 I->replaceAllUsesWith(I->getOperand(0));
1497 I->eraseFromParent();
1498 } else
1499 I->moveBefore(*FC1.ExitBlock, FC1.ExitBlock->getFirstInsertionPt());
1500 }
1501 }
1502
1503 /// Determine if two fusion candidates have identical guards
1504 ///
1505 /// This method will determine if two fusion candidates have the same guards.
1506 /// The guards are considered the same if:
1507 /// 1. The instructions to compute the condition used in the compare are
1508 /// identical.
1509 /// 2. The successors of the guard have the same flow into/around the loop.
1510 /// If the compare instructions are identical, then the first successor of the
1511 /// guard must go to the same place (either the preheader of the loop or the
1512 /// NonLoopBlock). In other words, the first successor of both loops must
1513 /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
1514 /// the NonLoopBlock). The same must be true for the second successor.
1515 bool haveIdenticalGuards(const FusionCandidate &FC0,
1516 const FusionCandidate &FC1) const {
1517 assert(FC0.GuardBranch && FC1.GuardBranch &&
1518 "Expecting FC0 and FC1 to be guarded loops.");
1519
1520 auto *FC0CmpInst = dyn_cast<Instruction>(FC0.GuardBranch->getCondition());
1521 auto *FC1CmpInst = dyn_cast<Instruction>(FC1.GuardBranch->getCondition());
1522 if ((!FC0CmpInst || !FC1CmpInst) &&
1523 FC0.GuardBranch->getCondition() != FC1.GuardBranch->getCondition())
1524 return false;
1525
1526 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1527 return false;
1528
1529 // The compare instructions are identical.
1530 // Now make sure the successor of the guards have the same flow into/around
1531 // the loop
1532 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1533 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1534 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1535 }
1536
1537 /// Modify the latch branch of FC to be unconditional since successors of the
1538 /// branch are the same.
1539 void simplifyLatchBranch(const FusionCandidate &FC) const {
1540 CondBrInst *FCLatchBranch = dyn_cast<CondBrInst>(FC.Latch->getTerminator());
1541 if (FCLatchBranch) {
1542 assert(FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
1543 "Expecting the two successors of FCLatchBranch to be the same");
1544 UncondBrInst *NewBranch =
1545 UncondBrInst::Create(FCLatchBranch->getSuccessor(0));
1546 ReplaceInstWithInst(FCLatchBranch, NewBranch);
1547 }
1548 }
1549
1550 /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique
1551 /// successor, then merge FC0.Latch with its unique successor.
1552 void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1553 moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI, SE);
1554 if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
1555 MergeBlockIntoPredecessor(Succ, &DTU, &LI);
1556 DTU.flush();
1557 }
1558 }
1559
1560 /// Move FC1's header PHIs into FC0's header, insert the loop-carried PHIs
1561 /// needed to keep SSA valid when FC0 exits without taking its back-edge, and
1562 /// rewire both latches to form the fused loop. Latch dominator-tree updates
1563 /// are appended to \p TreeUpdates for the caller to apply.
1564 void rewireFusedHeaderPHIsAndLatches(
1565 const FusionCandidate &FC0, const FusionCandidate &FC1,
1566 const SmallVectorImpl<PHINode *> &OriginalFC0PHIs,
1567 SmallVectorImpl<DominatorTree::UpdateType> &TreeUpdates) {
1568 // Moves the phi nodes from the second to the first loops header block.
1569 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1570 if (SE.isSCEVable(PHI->getType()))
1571 SE.forgetValue(PHI);
1572 if (PHI->hasNUsesOrMore(1))
1573 PHI->moveBefore(FC0.Header->getFirstInsertionPt());
1574 else
1575 PHI->eraseFromParent();
1576 }
1577
1578 // Introduce new phi nodes in the second loop header to ensure
1579 // exiting the first and jumping to the header of the second does not break
1580 // the SSA property of the phis originally in the first loop. See also the
1581 // comment above.
1582 BasicBlock::iterator L1HeaderIP = FC1.Header->begin();
1583 for (PHINode *LCPHI : OriginalFC0PHIs) {
1584 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1585 assert(L1LatchBBIdx >= 0 &&
1586 "Expected loop carried value to be rewired at this point!");
1587
1588 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1589
1590 PHINode *L1HeaderPHI =
1591 PHINode::Create(LCV->getType(), 2, LCPHI->getName() + ".afterFC0");
1592 L1HeaderPHI->insertBefore(L1HeaderIP);
1593 L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1594 L1HeaderPHI->addIncoming(PoisonValue::get(LCV->getType()),
1595 FC0.ExitingBlock);
1596
1597 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1598 }
1599
1600 // Replace latch terminator destinations.
1601 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1602 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1603
1604 // Modify the latch branch of FC0 to be unconditional as both successors of
1605 // the branch are the same.
1606 simplifyLatchBranch(FC0);
1607
1608 // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1609 // performed the updates above.
1610 if (FC0.Latch != FC0.ExitingBlock)
1611 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1612 DominatorTree::Insert, FC0.Latch, FC1.Header));
1613
1614 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1615 FC0.Latch, FC0.Header));
1616 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1617 FC1.Latch, FC0.Header));
1618 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1619 FC1.Latch, FC1.Header));
1620 }
1621
1622 /// Forget cached SCEV state for both loops, move all of FC1's blocks and
1623 /// child loops into FC0, erase the now-empty FC1, and merge the latches.
1624 /// Returns the fused loop (FC0.L).
1625 Loop *finalizeFusedLoop(const FusionCandidate &FC0,
1626 const FusionCandidate &FC1) {
1627 // Is there a way to keep SE up-to-date so we don't need to forget the loops
1628 // and rebuild the information in subsequent passes of fusion?
1629 // Note: Need to forget the loops before merging the loop latches, as
1630 // mergeLatch may remove the only block in FC1.
1631 SE.forgetLoop(FC1.L);
1632 SE.forgetLoop(FC0.L);
1633
1634 // Merge the loops.
1635 SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
1636 for (BasicBlock *BB : Blocks) {
1637 FC0.L->addBlockEntry(BB);
1638 FC1.L->removeBlockFromLoop(BB);
1639 if (LI.getLoopFor(BB) != FC1.L)
1640 continue;
1641 LI.changeLoopFor(BB, FC0.L);
1642 }
1643 while (!FC1.L->isInnermost()) {
1644 const auto &ChildLoopIt = FC1.L->begin();
1645 Loop *ChildLoop = *ChildLoopIt;
1646 FC1.L->removeChildLoop(ChildLoopIt);
1647 FC0.L->addChildLoop(ChildLoop);
1648 }
1649
1650 // Delete the now empty loop L1.
1651 LI.erase(FC1.L);
1652
1653 // Forget block dispositions as well, so that there are no dangling
1654 // pointers to erased/free'ed blocks. It should be done after mergeLatch()
1655 // since merging the latches may affect the dispositions.
1656 SE.forgetBlockAndLoopDispositions();
1657
1658 // Move instructions from FC0.Latch to FC1.Latch.
1659 // Note: mergeLatch requires an updated DT.
1660 mergeLatch(FC0, FC1);
1661
1662#ifndef NDEBUG
1663 assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1664 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1665 assert(PDT.verify());
1666 LI.verify();
1667 SE.verify();
1668#endif
1669
1670 LLVM_DEBUG(dbgs() << "Fusion done:\n");
1671
1672 return FC0.L;
1673 }
1674
1675 /// Fuse two fusion candidates, creating a new fused loop.
1676 ///
1677 /// This method contains the mechanics of fusing two loops, represented by \p
1678 /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
1679 /// postdominates \p FC0 (making them control flow equivalent). It also
1680 /// assumes that the other conditions for fusion have been met: adjacent,
1681 /// identical trip counts, and no negative distance dependencies exist that
1682 /// would prevent fusion. Thus, there is no checking for these conditions in
1683 /// this method.
1684 ///
1685 /// Fusion is performed by rewiring the CFG to update successor blocks of the
1686 /// components of tho loop. Specifically, the following changes are done:
1687 ///
1688 /// 1. The preheader of \p FC1 is removed as it is no longer necessary
1689 /// (because it is currently only a single statement block).
1690 /// 2. The latch of \p FC0 is modified to jump to the header of \p FC1.
1691 /// 3. The latch of \p FC1 i modified to jump to the header of \p FC0.
1692 /// 4. All blocks from \p FC1 are removed from FC1 and added to FC0.
1693 ///
1694 /// All of these modifications are done with dominator tree updates, thus
1695 /// keeping the dominator (and post dominator) information up-to-date.
1696 ///
1697 /// This can be improved in the future by actually merging blocks during
1698 /// fusion. For example, the preheader of \p FC1 can be merged with the
1699 /// preheader of \p FC0. This would allow loops with more than a single
1700 /// statement in the preheader to be fused. Similarly, the latch blocks of the
1701 /// two loops could also be fused into a single block. This will require
1702 /// analysis to prove it is safe to move the contents of the block past
1703 /// existing code, which currently has not been implemented.
1704 Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1705 assert(FC0.isValid() && FC1.isValid() &&
1706 "Expecting valid fusion candidates");
1707
1708 LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
1709 dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
1710
1711 // Move instructions from the preheader of FC1 to the end of the preheader
1712 // of FC0.
1713 moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI, SE);
1714
1715 // Fusing guarded loops is handled slightly differently than non-guarded
1716 // loops and has been broken out into a separate method instead of trying to
1717 // intersperse the logic within a single method.
1718 if (FC0.GuardBranch)
1719 return fuseGuardedLoops(FC0, FC1);
1720
1721 assert(FC1.Preheader ==
1722 (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
1723 assert(FC1.Preheader->size() == 1 &&
1724 FC1.Preheader->getSingleSuccessor() == FC1.Header);
1725
1726 // Remember the phi nodes originally in the header of FC0 in order to rewire
1727 // them later. However, this is only necessary if the new loop carried
1728 // values might not dominate the exiting branch. While we do not generally
1729 // test if this is the case but simply insert intermediate phi nodes, we
1730 // need to make sure these intermediate phi nodes have different
1731 // predecessors. To this end, we filter the special case where the exiting
1732 // block is the latch block of the first loop. Nothing needs to be done
1733 // anyway as all loop carried values dominate the latch and thereby also the
1734 // exiting branch.
1735 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1736 if (FC0.ExitingBlock != FC0.Latch)
1737 for (PHINode &PHI : FC0.Header->phis())
1738 OriginalFC0PHIs.push_back(&PHI);
1739
1740 // Replace incoming blocks for header PHIs first.
1741 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1742 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1743
1744 // Then modify the control flow and update DT and PDT.
1746
1747 // The old exiting block of the first loop (FC0) has to jump to the header
1748 // of the second as we need to execute the code in the second header block
1749 // regardless of the trip count. That is, if the trip count is 0, so the
1750 // back edge is never taken, we still have to execute both loop headers,
1751 // especially (but not only!) if the second is a do-while style loop.
1752 // However, doing so might invalidate the phi nodes of the first loop as
1753 // the new values do only need to dominate their latch and not the exiting
1754 // predicate. To remedy this potential problem we always introduce phi
1755 // nodes in the header of the second loop later that select the loop carried
1756 // value, if the second header was reached through an old latch of the
1757 // first, or undef otherwise. This is sound as exiting the first implies the
1758 // second will exit too, __without__ taking the back-edge. [Their
1759 // trip-counts are equal after all.
1760 // KB: Would this sequence be simpler to just make FC0.ExitingBlock go
1761 // to FC1.Header? I think this is basically what the three sequences are
1762 // trying to accomplish; however, doing this directly in the CFG may mean
1763 // the DT/PDT becomes invalid
1764 if (!FC0.Peeled) {
1765 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1766 FC1.Header);
1767 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1768 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1769 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1770 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1771 } else {
1772 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1773 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1774
1775 // Remove the ExitBlock of the first Loop (also not needed)
1776 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1777 FC1.Header);
1778 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1779 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1780 FC0.ExitBlock->getTerminator()->eraseFromParent();
1781 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1782 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1783 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1784 }
1785
1786 // The pre-header of L1 is not necessary anymore.
1787 assert(pred_empty(FC1.Preheader));
1788 FC1.Preheader->getTerminator()->eraseFromParent();
1789 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1790 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1791 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1792
1793 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
1794
1795 // Update DT/PDT
1796 DTU.applyUpdates(TreeUpdates);
1797
1798 LI.removeBlock(FC1.Preheader);
1799 DTU.deleteBB(FC1.Preheader);
1800 if (FC0.Peeled) {
1801 LI.removeBlock(FC0.ExitBlock);
1802 DTU.deleteBB(FC0.ExitBlock);
1803 }
1804
1805 DTU.flush();
1806
1807 return finalizeFusedLoop(FC0, FC1);
1808 }
1809
1810 /// Report details on loop fusion opportunities.
1811 ///
1812 /// This template function can be used to report both successful and missed
1813 /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
1814 /// be one of:
1815 /// - OptimizationRemarkMissed to report when loop fusion is unsuccessful
1816 /// given two valid fusion candidates.
1817 /// - OptimizationRemark to report successful fusion of two fusion
1818 /// candidates.
1819 /// The remarks will be printed using the form:
1820 /// <path/filename>:<line number>:<column number>: [<function name>]:
1821 /// <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
1822 template <typename RemarkKind>
1823 void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
1824 StringRef RemarkName, StringRef RemarkMsg) {
1825 assert(FC0.Preheader && FC1.Preheader &&
1826 "Expecting valid fusion candidates");
1827 using namespace ore;
1828 ORE.emit(
1829 RemarkKind(DEBUG_TYPE, RemarkName, FC0.L->getStartLoc(), FC0.Preheader)
1830 << "[" << FC0.Preheader->getParent()->getName()
1831 << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName())) << " and "
1832 << NV("Cand2", StringRef(FC1.Preheader->getName())) << ": "
1833 << RemarkMsg);
1834 }
1835
1836 void reportFusionInsufficientReuse(const FusionCandidate &FC0,
1837 const FusionCandidate &FC1,
1838 unsigned ReusedValueCount) {
1839 assert(ReusedValueCount < Opts.loop_fusion_min_reused_values &&
1840 "Expected insufficient reuse");
1841
1842 using namespace ore;
1843 ORE.emit(OptimizationRemarkMissed(DEBUG_TYPE, "InsufficientReuse",
1844 FC0.L->getStartLoc(), FC0.Preheader)
1845 << "[" << FC0.Preheader->getParent()->getName()
1846 << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
1847 << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
1848 << ": found " << NV("ReusedValueCount", ReusedValueCount)
1849 << " cross-loop reused values; configured minimum is "
1850 << NV("MinimumReusedValues",
1851 unsigned(Opts.loop_fusion_min_reused_values)));
1852 }
1853
1854 /// Fuse two guarded fusion candidates, creating a new fused loop.
1855 ///
1856 /// Fusing guarded loops is handled much the same way as fusing non-guarded
1857 /// loops. The rewiring of the CFG is slightly different though, because of
1858 /// the presence of the guards around the loops and the exit blocks after the
1859 /// loop body. As such, the new loop is rewired as follows:
1860 /// 1. Keep the guard branch from FC0 and use the non-loop block target
1861 /// from the FC1 guard branch.
1862 /// 2. Remove the exit block from FC0 (this exit block should be empty
1863 /// right now).
1864 /// 3. Remove the guard branch for FC1
1865 /// 4. Remove the preheader for FC1.
1866 /// The exit block successor for the latch of FC0 is updated to be the header
1867 /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
1868 /// be the header of FC0, thus creating the fused loop.
1869 Loop *fuseGuardedLoops(const FusionCandidate &FC0,
1870 const FusionCandidate &FC1) {
1871 assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
1872
1873 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1874 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1875 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1876 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1877 BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
1878
1879 // Move instructions from the exit block of FC0 to the beginning of the exit
1880 // block of FC1, in the case that the FC0 loop has not been peeled. In the
1881 // case that FC0 loop is peeled, then move the instructions of the successor
1882 // of the FC0 Exit block to the beginning of the exit block of FC1.
1884 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1885 DT, PDT, DI, SE);
1886
1887 // Move instructions from the guard block of FC1 to the end of the guard
1888 // block of FC0.
1889 moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI, SE);
1890
1891 assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
1892
1894
1895 ////////////////////////////////////////////////////////////////////////////
1896 // Update the Loop Guard
1897 ////////////////////////////////////////////////////////////////////////////
1898 // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
1899 // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
1900 // Thus, one path from the guard goes to the preheader for FC0 (and thus
1901 // executes the new fused loop) and the other path goes to the NonLoopBlock
1902 // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1903 FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
1904 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1905
1906 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1907 BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
1908
1909 // The guard of FC1 is not necessary anymore.
1910 FC1.GuardBranch->eraseFromParent();
1911 new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
1912
1913 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1914 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1915 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1916 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1917 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1918 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1919 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1920 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1921
1922 if (FC0.Peeled) {
1923 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1924 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1925 // Remove the Block after the ExitBlock of FC0
1926 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1927 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1928 FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
1929 new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
1930 FC0ExitBlockSuccessor);
1931 }
1932
1933 assert(pred_empty(FC1GuardBlock) &&
1934 "Expecting guard block to have no predecessors");
1935 assert(succ_empty(FC1GuardBlock) &&
1936 "Expecting guard block to have no successors");
1937
1938 // Remember the phi nodes originally in the header of FC0 in order to rewire
1939 // them later. However, this is only necessary if the new loop carried
1940 // values might not dominate the exiting branch. While we do not generally
1941 // test if this is the case but simply insert intermediate phi nodes, we
1942 // need to make sure these intermediate phi nodes have different
1943 // predecessors. To this end, we filter the special case where the exiting
1944 // block is the latch block of the first loop. Nothing needs to be done
1945 // anyway as all loop carried values dominate the latch and thereby also the
1946 // exiting branch.
1947 // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
1948 // (because the loops are rotated. Thus, nothing will ever be added to
1949 // OriginalFC0PHIs.
1950 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1951 if (FC0.ExitingBlock != FC0.Latch)
1952 for (PHINode &PHI : FC0.Header->phis())
1953 OriginalFC0PHIs.push_back(&PHI);
1954
1955 assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
1956
1957 // Replace incoming blocks for header PHIs first.
1958 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1959 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1960
1961 // The old exiting block of the first loop (FC0) has to jump to the header
1962 // of the second as we need to execute the code in the second header block
1963 // regardless of the trip count. That is, if the trip count is 0, so the
1964 // back edge is never taken, we still have to execute both loop headers,
1965 // especially (but not only!) if the second is a do-while style loop.
1966 // However, doing so might invalidate the phi nodes of the first loop as
1967 // the new values do only need to dominate their latch and not the exiting
1968 // predicate. To remedy this potential problem we always introduce phi
1969 // nodes in the header of the second loop later that select the loop carried
1970 // value, if the second header was reached through an old latch of the
1971 // first, or undef otherwise. This is sound as exiting the first implies the
1972 // second will exit too, __without__ taking the back-edge (their
1973 // trip-counts are equal after all).
1974 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1975 FC1.Header);
1976
1977 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1978 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1979 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1980 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1981
1982 // Remove FC0 Exit Block
1983 // The exit block for FC0 is no longer needed since control will flow
1984 // directly to the header of FC1. Since it is an empty block, it can be
1985 // removed at this point.
1986 // TODO: In the future, we can handle non-empty exit blocks my merging any
1987 // instructions from FC0 exit block into FC1 exit block prior to removing
1988 // the block.
1989 assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
1990 FC0.ExitBlock->getTerminator()->eraseFromParent();
1991 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1992
1993 // Remove FC1 Preheader
1994 // The pre-header of L1 is not necessary anymore.
1995 assert(pred_empty(FC1.Preheader));
1996 FC1.Preheader->getTerminator()->eraseFromParent();
1997 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1998 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1999 DominatorTree::Delete, FC1.Preheader, FC1.Header));
2000
2001 rewireFusedHeaderPHIsAndLatches(FC0, FC1, OriginalFC0PHIs, TreeUpdates);
2002
2003 // All done
2004 // Apply the updates to the Dominator Tree and cleanup.
2005
2006 assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
2007 assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
2008
2009 // Update DT/PDT
2010 DTU.applyUpdates(TreeUpdates);
2011
2012 LI.removeBlock(FC1GuardBlock);
2013 LI.removeBlock(FC1.Preheader);
2014 LI.removeBlock(FC0.ExitBlock);
2015 if (FC0.Peeled) {
2016 LI.removeBlock(FC0ExitBlockSuccessor);
2017 DTU.deleteBB(FC0ExitBlockSuccessor);
2018 }
2019 DTU.deleteBB(FC1GuardBlock);
2020 DTU.deleteBB(FC1.Preheader);
2021 DTU.deleteBB(FC0.ExitBlock);
2022 DTU.flush();
2023
2024 return finalizeFusedLoop(FC0, FC1);
2025 }
2026};
2027} // namespace
2028
2030 auto &LI = AM.getResult<LoopAnalysis>(F);
2031 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2032 auto &DI = AM.getResult<DependenceAnalysis>(F);
2033 auto &AA = AM.getResult<AAManager>(F);
2034 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
2035 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
2037 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2039
2040 // Ensure loops are in simplifed form which is a pre-requisite for loop fusion
2041 // pass. Added only for new PM since the legacy PM has already added
2042 // LoopSimplify pass as a dependency.
2043 bool Changed = false;
2044 DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Lazy);
2045 for (auto &L : LI) {
2046 Changed |=
2047 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
2048 }
2049 for (Loop *L : LI.getLoopsInPreorder()) {
2050 Changed |= simplifyLoopGuard(L, DTU, LI, SE);
2051 }
2052
2053 if (Changed)
2054 PDT.recalculate(F);
2055
2056 LoopFuser LF(ScalarOptions::Global, LI, DT, DI, AA, SE, PDT, ORE, AC, TTI);
2057 Changed |= LF.fuseLoops(F);
2058 if (!Changed)
2059 return PreservedAnalyses::all();
2060
2065 PA.preserve<LoopAnalysis>();
2066 return PA;
2067}
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< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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
This file defines the DenseMap class.
#define DEBUG_TYPE
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
Definition LoopFuse.cpp:395
std::list< FusionCandidate > FusionCandidateList
Definition LoopFuse.cpp:366
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:425
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
Definition LoopFuse.cpp:367
static void printLoopVector(const LoopVector &LV)
Definition LoopFuse.cpp:370
SmallVector< Loop *, 4 > LoopVector
Definition LoopFuse.cpp:361
#define DEBUG_TYPE
Definition LoopFuse.cpp:77
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 SmallPtrSet class.
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.
A manager for alias analyses.
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
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:794
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
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
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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
Abstract Attribute helper functions.
Definition Attributor.h:165
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ Valid
The data is already valid.
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
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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.
@ Load
The value being inserted comes from a load (InsertElement only).
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)
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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...