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