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