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