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