forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoopFuse.cpp
1896 lines (1659 loc) · 77.9 KB
/
LoopFuse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- LoopFuse.cpp - Loop Fusion Pass ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the loop fusion pass.
/// The implementation is largely based on the following document:
///
/// Code Transformations to Augment the Scope of Loop Fusion in a
/// Production Compiler
/// Christopher Mark Barton
/// MSc Thesis
/// https://webdocs.cs.ualberta.ca/~amaral/thesis/ChristopherBartonMSc.pdf
///
/// The general approach taken is to collect sets of control flow equivalent
/// loops and test whether they can be fused. The necessary conditions for
/// fusion are:
/// 1. The loops must be adjacent (there cannot be any statements between
/// the two loops).
/// 2. The loops must be conforming (they must execute the same number of
/// iterations).
/// 3. The loops must be control flow equivalent (if one loop executes, the
/// other is guaranteed to execute).
/// 4. There cannot be any negative distance dependencies between the loops.
/// If all of these conditions are satisfied, it is safe to fuse the loops.
///
/// This implementation creates FusionCandidates that represent the loop and the
/// necessary information needed by fusion. It then operates on the fusion
/// candidates, first confirming that the candidate is eligible for fusion. The
/// candidates are then collected into control flow equivalent sets, sorted in
/// dominance order. Each set of control flow equivalent candidates is then
/// traversed, attempting to fuse pairs of candidates in the set. If all
/// requirements for fusion are met, the two candidates are fused, creating a
/// new (fused) candidate which is then added back into the set to consider for
/// additional fusion.
///
/// This implementation currently does not make any modifications to remove
/// conditions for fusion. Code transformations to make loops conform to each of
/// the conditions for fusion are discussed in more detail in the document
/// above. These can be added to the current implementation in the future.
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/LoopFuse.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Verifier.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/CodeMoverUtils.h"
#include "llvm/Transforms/Utils/LoopPeel.h"
using namespace llvm;
#define DEBUG_TYPE "loop-fusion"
STATISTIC(FuseCounter, "Loops fused");
STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
STATISTIC(InvalidPreheader, "Loop has invalid preheader");
STATISTIC(InvalidHeader, "Loop has invalid header");
STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
STATISTIC(InvalidLatch, "Loop has invalid latch");
STATISTIC(InvalidLoop, "Loop is invalid");
STATISTIC(AddressTakenBB, "Basic block has address taken");
STATISTIC(MayThrowException, "Loop may throw an exception");
STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
STATISTIC(UnknownTripCount, "Loop has unknown trip count");
STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
STATISTIC(NonAdjacent, "Loops are not adjacent");
STATISTIC(
NonEmptyPreheader,
"Loop has a non-empty preheader with instructions that cannot be moved");
STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
STATISTIC(NonIdenticalGuards, "Candidates have different guards");
STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
"instructions that cannot be moved");
STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
"instructions that cannot be moved");
STATISTIC(NotRotated, "Candidate is not rotated");
STATISTIC(OnlySecondCandidateIsGuarded,
"The second candidate is guarded while the first one is not");
enum FusionDependenceAnalysisChoice {
FUSION_DEPENDENCE_ANALYSIS_SCEV,
FUSION_DEPENDENCE_ANALYSIS_DA,
FUSION_DEPENDENCE_ANALYSIS_ALL,
};
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), cl::ZeroOrMore);
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"));
#ifndef NDEBUG
static cl::opt<bool>
VerboseFusionDebugging("loop-fusion-verbose-debug",
cl::desc("Enable verbose debugging for Loop Fusion"),
cl::Hidden, cl::init(false), cl::ZeroOrMore);
#endif
namespace {
/// This class is used to represent a candidate for loop fusion. When it is
/// constructed, it checks the conditions for loop fusion to ensure that it
/// represents a valid candidate. It caches several parts of a loop that are
/// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
/// of continually querying the underlying Loop to retrieve these values. It is
/// assumed these will not change throughout loop fusion.
///
/// The invalidate method should be used to indicate that the FusionCandidate is
/// no longer a valid candidate for fusion. Similarly, the isValid() method can
/// be used to ensure that the FusionCandidate is still valid for fusion.
struct FusionCandidate {
/// Cache of parts of the loop used throughout loop fusion. These should not
/// need to change throughout the analysis and transformation.
/// These parts are cached to avoid repeatedly looking up in the Loop class.
/// Preheader of the loop this candidate represents
BasicBlock *Preheader;
/// Header of the loop this candidate represents
BasicBlock *Header;
/// Blocks in the loop that exit the loop
BasicBlock *ExitingBlock;
/// The successor block of this loop (where the exiting blocks go to)
BasicBlock *ExitBlock;
/// Latch of the loop
BasicBlock *Latch;
/// The loop that this fusion candidate represents
Loop *L;
/// Vector of instructions in this loop that read from memory
SmallVector<Instruction *, 16> MemReads;
/// Vector of instructions in this loop that write to memory
SmallVector<Instruction *, 16> MemWrites;
/// Are all of the members of this fusion candidate still valid
bool Valid;
/// Guard branch of the loop, if it exists
BranchInst *GuardBranch;
/// Peeling Paramaters of the Loop.
TTI::PeelingPreferences PP;
/// Can you Peel this Loop?
bool AbleToPeel;
/// Has this loop been Peeled
bool Peeled;
/// Dominator and PostDominator trees are needed for the
/// FusionCandidateCompare function, required by FusionCandidateSet to
/// determine where the FusionCandidate should be inserted into the set. These
/// are used to establish ordering of the FusionCandidates based on dominance.
const DominatorTree *DT;
const PostDominatorTree *PDT;
OptimizationRemarkEmitter &ORE;
FusionCandidate(Loop *L, const DominatorTree *DT,
const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE,
TTI::PeelingPreferences PP)
: Preheader(L->getLoopPreheader()), Header(L->getHeader()),
ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
Latch(L->getLoopLatch()), L(L), Valid(true),
GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
// Walk over all blocks in the loop and check for conditions that may
// prevent fusion. For each block, walk over all instructions and collect
// the memory reads and writes If any instructions that prevent fusion are
// found, invalidate this object and return.
for (BasicBlock *BB : L->blocks()) {
if (BB->hasAddressTaken()) {
invalidate();
reportInvalidCandidate(AddressTakenBB);
return;
}
for (Instruction &I : *BB) {
if (I.mayThrow()) {
invalidate();
reportInvalidCandidate(MayThrowException);
return;
}
if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
if (SI->isVolatile()) {
invalidate();
reportInvalidCandidate(ContainsVolatileAccess);
return;
}
}
if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
if (LI->isVolatile()) {
invalidate();
reportInvalidCandidate(ContainsVolatileAccess);
return;
}
}
if (I.mayWriteToMemory())
MemWrites.push_back(&I);
if (I.mayReadFromMemory())
MemReads.push_back(&I);
}
}
}
/// Check if all members of the class are valid.
bool isValid() const {
return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
!L->isInvalid() && Valid;
}
/// Verify that all members are in sync with the Loop object.
void verify() const {
assert(isValid() && "Candidate is not valid!!");
assert(!L->isInvalid() && "Loop is invalid!");
assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
assert(Header == L->getHeader() && "Header is out of sync");
assert(ExitingBlock == L->getExitingBlock() &&
"Exiting Blocks is out of sync");
assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
assert(Latch == L->getLoopLatch() && "Latch is out of sync");
}
/// Get the entry block for this fusion candidate.
///
/// If this fusion candidate represents a guarded loop, the entry block is the
/// loop guard block. If it represents an unguarded loop, the entry block is
/// the preheader of the loop.
BasicBlock *getEntryBlock() const {
if (GuardBranch)
return GuardBranch->getParent();
else
return Preheader;
}
/// After Peeling the loop is modified quite a bit, hence all of the Blocks
/// need to be updated accordingly.
void updateAfterPeeling() {
Preheader = L->getLoopPreheader();
Header = L->getHeader();
ExitingBlock = L->getExitingBlock();
ExitBlock = L->getExitBlock();
Latch = L->getLoopLatch();
verify();
}
/// Given a guarded loop, get the successor of the guard that is not in the
/// loop.
///
/// This method returns the successor of the loop guard that is not located
/// within the loop (i.e., the successor of the guard that is not the
/// preheader).
/// This method is only valid for guarded loops.
BasicBlock *getNonLoopBlock() const {
assert(GuardBranch && "Only valid on guarded loops.");
assert(GuardBranch->isConditional() &&
"Expecting guard to be a conditional branch.");
if (Peeled)
return GuardBranch->getSuccessor(1);
return (GuardBranch->getSuccessor(0) == Preheader)
? GuardBranch->getSuccessor(1)
: GuardBranch->getSuccessor(0);
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void dump() const {
dbgs() << "\tGuardBranch: ";
if (GuardBranch)
dbgs() << *GuardBranch;
else
dbgs() << "nullptr";
dbgs() << "\n"
<< (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
<< "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
<< "\n"
<< "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
<< "\tExitingBB: "
<< (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
<< "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
<< "\n"
<< "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
<< "\tEntryBlock: "
<< (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
<< "\n";
}
#endif
/// Determine if a fusion candidate (representing a loop) is eligible for
/// fusion. Note that this only checks whether a single loop can be fused - it
/// does not check whether it is *legal* to fuse two loops together.
bool isEligibleForFusion(ScalarEvolution &SE) const {
if (!isValid()) {
LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
if (!Preheader)
++InvalidPreheader;
if (!Header)
++InvalidHeader;
if (!ExitingBlock)
++InvalidExitingBlock;
if (!ExitBlock)
++InvalidExitBlock;
if (!Latch)
++InvalidLatch;
if (L->isInvalid())
++InvalidLoop;
return false;
}
// Require ScalarEvolution to be able to determine a trip count.
if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName()
<< " trip count not computable!\n");
return reportInvalidCandidate(UnknownTripCount);
}
if (!L->isLoopSimplifyForm()) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName()
<< " is not in simplified form!\n");
return reportInvalidCandidate(NotSimplifiedForm);
}
if (!L->isRotatedForm()) {
LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
return reportInvalidCandidate(NotRotated);
}
return true;
}
private:
// This is only used internally for now, to clear the MemWrites and MemReads
// list and setting Valid to false. I can't envision other uses of this right
// now, since once FusionCandidates are put into the FusionCandidateSet they
// are immutable. Thus, any time we need to change/update a FusionCandidate,
// we must create a new one and insert it into the FusionCandidateSet to
// ensure the FusionCandidateSet remains ordered correctly.
void invalidate() {
MemWrites.clear();
MemReads.clear();
Valid = false;
}
bool reportInvalidCandidate(llvm::Statistic &Stat) const {
using namespace ore;
assert(L && Preheader && "Fusion candidate not initialized properly!");
#if LLVM_ENABLE_STATS
++Stat;
ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
L->getStartLoc(), Preheader)
<< "[" << Preheader->getParent()->getName() << "]: "
<< "Loop is not a candidate for fusion: " << Stat.getDesc());
#endif
return false;
}
};
struct FusionCandidateCompare {
/// Comparison functor to sort two Control Flow Equivalent fusion candidates
/// into dominance order.
/// If LHS dominates RHS and RHS post-dominates LHS, return true;
/// IF RHS dominates LHS and LHS post-dominates RHS, return false;
bool operator()(const FusionCandidate &LHS,
const FusionCandidate &RHS) const {
const DominatorTree *DT = LHS.DT;
BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
// Do not save PDT to local variable as it is only used in asserts and thus
// will trigger an unused variable warning if building without asserts.
assert(DT && LHS.PDT && "Expecting valid dominator tree");
// Do this compare first so if LHS == RHS, function returns false.
if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
// RHS dominates LHS
// Verify LHS post-dominates RHS
assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
return false;
}
if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
// Verify RHS Postdominates LHS
assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
return true;
}
// If LHS does not dominate RHS and RHS does not dominate LHS then there is
// no dominance relationship between the two FusionCandidates. Thus, they
// should not be in the same set together.
llvm_unreachable(
"No dominance relationship between these fusion candidates!");
}
};
using LoopVector = SmallVector<Loop *, 4>;
// Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
// order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
// dominates FC1 and FC1 post-dominates FC0.
// std::set was chosen because we want a sorted data structure with stable
// iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
// loops by moving intervening code around. When this intervening code contains
// loops, those loops will be moved also. The corresponding FusionCandidates
// will also need to be moved accordingly. As this is done, having stable
// iterators will simplify the logic. Similarly, having an efficient insert that
// keeps the FusionCandidateSet sorted will also simplify the implementation.
using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
#if !defined(NDEBUG)
static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const FusionCandidate &FC) {
if (FC.isValid())
OS << FC.Preheader->getName();
else
OS << "<Invalid>";
return OS;
}
static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const FusionCandidateSet &CandSet) {
for (const FusionCandidate &FC : CandSet)
OS << FC << '\n';
return OS;
}
static void
printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
dbgs() << "Fusion Candidates: \n";
for (const auto &CandidateSet : FusionCandidates) {
dbgs() << "*** Fusion Candidate Set ***\n";
dbgs() << CandidateSet;
dbgs() << "****************************\n";
}
}
#endif
/// Collect all loops in function at the same nest level, starting at the
/// outermost level.
///
/// This data structure collects all loops at the same nest level for a
/// given function (specified by the LoopInfo object). It starts at the
/// outermost level.
struct LoopDepthTree {
using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
using iterator = LoopsOnLevelTy::iterator;
using const_iterator = LoopsOnLevelTy::const_iterator;
LoopDepthTree(LoopInfo &LI) : Depth(1) {
if (!LI.empty())
LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
}
/// Test whether a given loop has been removed from the function, and thus is
/// no longer valid.
bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
/// Record that a given loop has been removed from the function and is no
/// longer valid.
void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
/// Descend the tree to the next (inner) nesting level
void descend() {
LoopsOnLevelTy LoopsOnNextLevel;
for (const LoopVector &LV : *this)
for (Loop *L : LV)
if (!isRemovedLoop(L) && L->begin() != L->end())
LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
LoopsOnLevel = LoopsOnNextLevel;
RemovedLoops.clear();
Depth++;
}
bool empty() const { return size() == 0; }
size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
unsigned getDepth() const { return Depth; }
iterator begin() { return LoopsOnLevel.begin(); }
iterator end() { return LoopsOnLevel.end(); }
const_iterator begin() const { return LoopsOnLevel.begin(); }
const_iterator end() const { return LoopsOnLevel.end(); }
private:
/// Set of loops that have been removed from the function and are no longer
/// valid.
SmallPtrSet<const Loop *, 8> RemovedLoops;
/// Depth of the current level, starting at 1 (outermost loops).
unsigned Depth;
/// Vector of loops at the current depth level that have the same parent loop
LoopsOnLevelTy LoopsOnLevel;
};
#ifndef NDEBUG
static void printLoopVector(const LoopVector &LV) {
dbgs() << "****************************\n";
for (auto L : LV)
printLoop(*L, dbgs());
dbgs() << "****************************\n";
}
#endif
struct LoopFuser {
private:
// Sets of control flow equivalent fusion candidates for a given nest level.
FusionCandidateCollection FusionCandidates;
LoopDepthTree LDT;
DomTreeUpdater DTU;
LoopInfo &LI;
DominatorTree &DT;
DependenceInfo &DI;
ScalarEvolution &SE;
PostDominatorTree &PDT;
OptimizationRemarkEmitter &ORE;
AssumptionCache &AC;
const TargetTransformInfo &TTI;
public:
LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
ScalarEvolution &SE, PostDominatorTree &PDT,
OptimizationRemarkEmitter &ORE, const DataLayout &DL,
AssumptionCache &AC, const TargetTransformInfo &TTI)
: LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
/// This is the main entry point for loop fusion. It will traverse the
/// specified function and collect candidate loops to fuse, starting at the
/// outermost nesting level and working inwards.
bool fuseLoops(Function &F) {
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LI.print(dbgs());
}
#endif
LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
<< "\n");
bool Changed = false;
while (!LDT.empty()) {
LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
<< LDT.getDepth() << "\n";);
for (const LoopVector &LV : LDT) {
assert(LV.size() > 0 && "Empty loop set was build!");
// Skip singleton loop sets as they do not offer fusion opportunities on
// this level.
if (LV.size() == 1)
continue;
#ifndef NDEBUG
if (VerboseFusionDebugging) {
LLVM_DEBUG({
dbgs() << " Visit loop set (#" << LV.size() << "):\n";
printLoopVector(LV);
});
}
#endif
collectFusionCandidates(LV);
Changed |= fuseCandidates();
}
// Finished analyzing candidates at this level.
// Descend to the next level and clear all of the candidates currently
// collected. Note that it will not be possible to fuse any of the
// existing candidates with new candidates because the new candidates will
// be at a different nest level and thus not be control flow equivalent
// with all of the candidates collected so far.
LLVM_DEBUG(dbgs() << "Descend one level!\n");
LDT.descend();
FusionCandidates.clear();
}
if (Changed)
LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
#ifndef NDEBUG
assert(DT.verify());
assert(PDT.verify());
LI.verify(DT);
SE.verify();
#endif
LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
return Changed;
}
private:
/// Determine if two fusion candidates are control flow equivalent.
///
/// Two fusion candidates are control flow equivalent if when one executes,
/// the other is guaranteed to execute. This is determined using dominators
/// and post-dominators: if A dominates B and B post-dominates A then A and B
/// are control-flow equivalent.
bool isControlFlowEquivalent(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
DT, PDT);
}
/// Iterate over all loops in the given loop set and identify the loops that
/// are eligible for fusion. Place all eligible fusion candidates into Control
/// Flow Equivalent sets, sorted by dominance.
void collectFusionCandidates(const LoopVector &LV) {
for (Loop *L : LV) {
TTI::PeelingPreferences PP =
gatherPeelingPreferences(L, SE, TTI, None, None);
FusionCandidate CurrCand(L, &DT, &PDT, ORE, PP);
if (!CurrCand.isEligibleForFusion(SE))
continue;
// Go through each list in FusionCandidates and determine if L is control
// flow equivalent with the first loop in that list. If it is, append LV.
// If not, go to the next list.
// If no suitable list is found, start another list and add it to
// FusionCandidates.
bool FoundSet = false;
for (auto &CurrCandSet : FusionCandidates) {
if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
CurrCandSet.insert(CurrCand);
FoundSet = true;
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << "Adding " << CurrCand
<< " to existing candidate set\n");
#endif
break;
}
}
if (!FoundSet) {
// No set was found. Create a new set and add to FusionCandidates
#ifndef NDEBUG
if (VerboseFusionDebugging)
LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
#endif
FusionCandidateSet NewCandSet;
NewCandSet.insert(CurrCand);
FusionCandidates.push_back(NewCandSet);
}
NumFusionCandidates++;
}
}
/// Determine if it is beneficial to fuse two loops.
///
/// For now, this method simply returns true because we want to fuse as much
/// as possible (primarily to test the pass). This method will evolve, over
/// time, to add heuristics for profitability of fusion.
bool isBeneficialFusion(const FusionCandidate &FC0,
const FusionCandidate &FC1) {
return true;
}
/// Determine if two fusion candidates have the same trip count (i.e., they
/// execute the same number of iterations).
///
/// This function will return a pair of values. The first is a boolean,
/// stating whether or not the two candidates are known at compile time to
/// have the same TripCount. The second is the difference in the two
/// TripCounts. This information can be used later to determine whether or not
/// peeling can be performed on either one of the candiates.
std::pair<bool, Optional<unsigned>>
haveIdenticalTripCounts(const FusionCandidate &FC0,
const FusionCandidate &FC1) const {
const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
if (isa<SCEVCouldNotCompute>(TripCount0)) {
UncomputableTripCount++;
LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
return {false, None};
}
const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
if (isa<SCEVCouldNotCompute>(TripCount1)) {
UncomputableTripCount++;
LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
return {false, None};
}
LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
<< *TripCount1 << " are "
<< (TripCount0 == TripCount1 ? "identical" : "different")
<< "\n");
if (TripCount0 == TripCount1)
return {true, 0};
LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
"determining the difference between trip counts\n");
// Currently only considering loops with a single exit point
// and a non-constant trip count.
const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
// If any of the tripcounts are zero that means that loop(s) do not have
// a single exit or a constant tripcount.
if (TC0 == 0 || TC1 == 0) {
LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
"have a constant number of iterations. Peeling "
"is not benefical\n");
return {false, None};
}
Optional<unsigned> Difference = None;
int Diff = TC0 - TC1;
if (Diff > 0)
Difference = Diff;
else {
LLVM_DEBUG(
dbgs() << "Difference is less than 0. FC1 (second loop) has more "
"iterations than the first one. Currently not supported\n");
}
LLVM_DEBUG(dbgs() << "Difference in loop trip count is: " << Difference
<< "\n");
return {false, Difference};
}
void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
unsigned PeelCount) {
assert(FC0.AbleToPeel && "Should be able to peel loop");
LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
<< " iterations of the first loop. \n");
FC0.Peeled = peelLoop(FC0.L, PeelCount, &LI, &SE, &DT, &AC, true);
if (FC0.Peeled) {
LLVM_DEBUG(dbgs() << "Done Peeling\n");
#ifndef NDEBUG
auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
"Loops should have identical trip counts after peeling");
#endif
FC0.PP.PeelCount += PeelCount;
// Peeling does not update the PDT
PDT.recalculate(*FC0.Preheader->getParent());
FC0.updateAfterPeeling();
// In this case the iterations of the loop are constant, so the first
// loop will execute completely (will not jump from one of
// the peeled blocks to the second loop). Here we are updating the
// branch conditions of each of the peeled blocks, such that it will
// branch to its successor which is not the preheader of the second loop
// in the case of unguarded loops, or the succesors of the exit block of
// the first loop otherwise. Doing this update will ensure that the entry
// block of the first loop dominates the entry block of the second loop.
BasicBlock *BB =
FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
if (BB) {
SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
SmallVector<Instruction *, 8> WorkList;
for (BasicBlock *Pred : predecessors(BB)) {
if (Pred != FC0.ExitBlock) {
WorkList.emplace_back(Pred->getTerminator());
TreeUpdates.emplace_back(
DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
}
}
// Cannot modify the predecessors inside the above loop as it will cause
// the iterators to be nullptrs, causing memory errors.
for (Instruction *CurrentBranch: WorkList) {
BasicBlock *Succ = CurrentBranch->getSuccessor(0);
if (Succ == BB)
Succ = CurrentBranch->getSuccessor(1);
ReplaceInstWithInst(CurrentBranch, BranchInst::Create(Succ));
}
DTU.applyUpdates(TreeUpdates);
DTU.flush();
}
LLVM_DEBUG(
dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
<< " iterations from the first loop.\n"
"Both Loops have the same number of iterations now.\n");
}
}
/// Walk each set of control flow equivalent fusion candidates and attempt to
/// fuse them. This does a single linear traversal of all candidates in the
/// set. The conditions for legal fusion are checked at this point. If a pair
/// of fusion candidates passes all legality checks, they are fused together
/// and a new fusion candidate is created and added to the FusionCandidateSet.
/// The original fusion candidates are then removed, as they are no longer
/// valid.
bool fuseCandidates() {
bool Fused = false;
LLVM_DEBUG(printFusionCandidates(FusionCandidates));
for (auto &CandidateSet : FusionCandidates) {
if (CandidateSet.size() < 2)
continue;
LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
<< CandidateSet << "\n");
for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
assert(!LDT.isRemovedLoop(FC0->L) &&
"Should not have removed loops in CandidateSet!");
auto FC1 = FC0;
for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
assert(!LDT.isRemovedLoop(FC1->L) &&
"Should not have removed loops in CandidateSet!");
LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
FC0->verify();
FC1->verify();
// Check if the candidates have identical tripcounts (first value of
// pair), and if not check the difference in the tripcounts between
// the loops (second value of pair). The difference is not equal to
// None iff the loops iterate a constant number of times, and have a
// single exit.
std::pair<bool, Optional<unsigned>> IdenticalTripCountRes =
haveIdenticalTripCounts(*FC0, *FC1);
bool SameTripCount = IdenticalTripCountRes.first;
Optional<unsigned> TCDifference = IdenticalTripCountRes.second;
// Here we are checking that FC0 (the first loop) can be peeled, and
// both loops have different tripcounts.
if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
if (*TCDifference > FusionPeelMaxCount) {
LLVM_DEBUG(dbgs()
<< "Difference in loop trip counts: " << *TCDifference
<< " is greater than maximum peel count specificed: "
<< FusionPeelMaxCount << "\n");
} else {
// Dependent on peeling being performed on the first loop, and
// assuming all other conditions for fusion return true.
SameTripCount = true;
}
}
if (!SameTripCount) {
LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
"counts. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEqualTripCount);
continue;
}
if (!isAdjacent(*FC0, *FC1)) {
LLVM_DEBUG(dbgs()
<< "Fusion candidates are not adjacent. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
continue;
}
if (!FC0->GuardBranch && FC1->GuardBranch) {
LLVM_DEBUG(dbgs() << "The second candidate is guarded while the "
"first one is not. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(
*FC0, *FC1, OnlySecondCandidateIsGuarded);
continue;
}
// Ensure that FC0 and FC1 have identical guards.
// If one (or both) are not guarded, this check is not necessary.
if (FC0->GuardBranch && FC1->GuardBranch &&
!haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
"guards. Not Fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonIdenticalGuards);
continue;
}
if (!isSafeToMoveBefore(*FC1->Preheader,
*FC0->Preheader->getTerminator(), DT, &PDT,
&DI)) {
LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
"instructions in preheader. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyPreheader);
continue;
}
if (FC0->GuardBranch) {
assert(FC1->GuardBranch && "Expecting valid FC1 guard branch");
if (!isSafeToMoveBefore(*FC0->ExitBlock,
*FC1->ExitBlock->getFirstNonPHIOrDbg(), DT,
&PDT, &DI)) {
LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
"instructions in exit block. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyExitBlock);
continue;
}
if (!isSafeToMoveBefore(
*FC1->GuardBranch->getParent(),
*FC0->GuardBranch->getParent()->getTerminator(), DT, &PDT,
&DI)) {
LLVM_DEBUG(dbgs()
<< "Fusion candidate contains unsafe "
"instructions in guard block. Not fusing.\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
NonEmptyGuardBlock);
continue;
}
}
// Check the dependencies across the loops and do not fuse if it would
// violate them.
if (!dependencesAllowFusion(*FC0, *FC1)) {
LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
InvalidDependencies);
continue;
}
bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
LLVM_DEBUG(dbgs()
<< "\tFusion appears to be "
<< (BeneficialToFuse ? "" : "un") << "profitable!\n");
if (!BeneficialToFuse) {
reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
FusionNotBeneficial);
continue;
}
// All analysis has completed and has determined that fusion is legal
// and profitable. At this point, start transforming the code and
// perform fusion.
LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
<< *FC1 << "\n");
FusionCandidate FC0Copy = *FC0;
// Peel the loop after determining that fusion is legal. The Loops
// will still be safe to fuse after the peeling is performed.
bool Peel = TCDifference && *TCDifference > 0;
if (Peel)
peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
// Report fusion to the Optimization Remarks.
// Note this needs to be done *before* performFusion because
// performFusion will change the original loops, making it not
// possible to identify them after fusion is complete.
reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
FuseCounter);
FusionCandidate FusedCand(
performFusion((Peel ? FC0Copy : *FC0), *FC1), &DT, &PDT, ORE,
FC0Copy.PP);
FusedCand.verify();
assert(FusedCand.isEligibleForFusion(SE) &&
"Fused candidate should be eligible for fusion!");
// Notify the loop-depth-tree that these loops are not valid objects
LDT.removeLoop(FC1->L);