xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopSink.cpp (revision 54711a6a5872d5f97da4c0a1bd7e58d0546ca701)
1 //===-- LoopSink.cpp - Loop Sink 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 // This pass does the inverse transformation of what LICM does.
10 // It traverses all of the instructions in the loop's preheader and sinks
11 // them to the loop body where frequency is lower than the loop's preheader.
12 // This pass is a reverse-transformation of LICM. It differs from the Sink
13 // pass in the following ways:
14 //
15 // * It only handles sinking of instructions from the loop's preheader to the
16 //   loop's body
17 // * It uses alias set tracker to get more accurate alias info
18 // * It uses block frequency info to find the optimal sinking locations
19 //
20 // Overall algorithm:
21 //
22 // For I in Preheader:
23 //   InsertBBs = BBs that uses I
24 //   For BB in sorted(LoopBBs):
25 //     DomBBs = BBs in InsertBBs that are dominated by BB
26 //     if freq(DomBBs) > freq(BB)
27 //       InsertBBs = UseBBs - DomBBs + BB
28 //   For BB in InsertBBs:
29 //     Insert I at BB's beginning
30 //
31 //===----------------------------------------------------------------------===//
32 
33 #include "llvm/Transforms/Scalar/LoopSink.h"
34 #include "llvm/ADT/SetOperations.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/BlockFrequencyInfo.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/MemorySSA.h"
41 #include "llvm/Analysis/MemorySSAUpdater.h"
42 #include "llvm/Analysis/ScalarEvolution.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/InitializePasses.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Transforms/Utils/LoopUtils.h"
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "loopsink"
54 
55 STATISTIC(NumLoopSunk, "Number of instructions sunk into loop");
56 STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop");
57 
58 static cl::opt<unsigned> SinkFrequencyPercentThreshold(
59     "sink-freq-percent-threshold", cl::Hidden, cl::init(90),
60     cl::desc("Do not sink instructions that require cloning unless they "
61              "execute less than this percent of the time."));
62 
63 static cl::opt<unsigned> MaxNumberOfUseBBsForSinking(
64     "max-uses-for-sinking", cl::Hidden, cl::init(30),
65     cl::desc("Do not sink instructions that have too many uses."));
66 
67 /// Return adjusted total frequency of \p BBs.
68 ///
69 /// * If there is only one BB, sinking instruction will not introduce code
70 ///   size increase. Thus there is no need to adjust the frequency.
71 /// * If there are more than one BB, sinking would lead to code size increase.
72 ///   In this case, we add some "tax" to the total frequency to make it harder
73 ///   to sink. E.g.
74 ///     Freq(Preheader) = 100
75 ///     Freq(BBs) = sum(50, 49) = 99
76 ///   Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to
77 ///   BBs as the difference is too small to justify the code size increase.
78 ///   To model this, The adjusted Freq(BBs) will be:
79 ///     AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold%
80 static BlockFrequency adjustedSumFreq(SmallPtrSetImpl<BasicBlock *> &BBs,
81                                       BlockFrequencyInfo &BFI) {
82   BlockFrequency T = 0;
83   for (BasicBlock *B : BBs)
84     T += BFI.getBlockFreq(B);
85   if (BBs.size() > 1)
86     T /= BranchProbability(SinkFrequencyPercentThreshold, 100);
87   return T;
88 }
89 
90 /// Return a set of basic blocks to insert sinked instructions.
91 ///
92 /// The returned set of basic blocks (BBsToSinkInto) should satisfy:
93 ///
94 /// * Inside the loop \p L
95 /// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto
96 ///   that domintates the UseBB
97 /// * Has minimum total frequency that is no greater than preheader frequency
98 ///
99 /// The purpose of the function is to find the optimal sinking points to
100 /// minimize execution cost, which is defined as "sum of frequency of
101 /// BBsToSinkInto".
102 /// As a result, the returned BBsToSinkInto needs to have minimum total
103 /// frequency.
104 /// Additionally, if the total frequency of BBsToSinkInto exceeds preheader
105 /// frequency, the optimal solution is not sinking (return empty set).
106 ///
107 /// \p ColdLoopBBs is used to help find the optimal sinking locations.
108 /// It stores a list of BBs that is:
109 ///
110 /// * Inside the loop \p L
111 /// * Has a frequency no larger than the loop's preheader
112 /// * Sorted by BB frequency
113 ///
114 /// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()).
115 /// To avoid expensive computation, we cap the maximum UseBBs.size() in its
116 /// caller.
117 static SmallPtrSet<BasicBlock *, 2>
118 findBBsToSinkInto(const Loop &L, const SmallPtrSetImpl<BasicBlock *> &UseBBs,
119                   const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
120                   DominatorTree &DT, BlockFrequencyInfo &BFI) {
121   SmallPtrSet<BasicBlock *, 2> BBsToSinkInto;
122   if (UseBBs.size() == 0)
123     return BBsToSinkInto;
124 
125   BBsToSinkInto.insert(UseBBs.begin(), UseBBs.end());
126   SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB;
127 
128   // For every iteration:
129   //   * Pick the ColdestBB from ColdLoopBBs
130   //   * Find the set BBsDominatedByColdestBB that satisfy:
131   //     - BBsDominatedByColdestBB is a subset of BBsToSinkInto
132   //     - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB
133   //   * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove
134   //     BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to
135   //     BBsToSinkInto
136   for (BasicBlock *ColdestBB : ColdLoopBBs) {
137     BBsDominatedByColdestBB.clear();
138     for (BasicBlock *SinkedBB : BBsToSinkInto)
139       if (DT.dominates(ColdestBB, SinkedBB))
140         BBsDominatedByColdestBB.insert(SinkedBB);
141     if (BBsDominatedByColdestBB.size() == 0)
142       continue;
143     if (adjustedSumFreq(BBsDominatedByColdestBB, BFI) >
144         BFI.getBlockFreq(ColdestBB)) {
145       for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) {
146         BBsToSinkInto.erase(DominatedBB);
147       }
148       BBsToSinkInto.insert(ColdestBB);
149     }
150   }
151 
152   // Can't sink into blocks that have no valid insertion point.
153   for (BasicBlock *BB : BBsToSinkInto) {
154     if (BB->getFirstInsertionPt() == BB->end()) {
155       BBsToSinkInto.clear();
156       break;
157     }
158   }
159 
160   // If the total frequency of BBsToSinkInto is larger than preheader frequency,
161   // do not sink.
162   if (adjustedSumFreq(BBsToSinkInto, BFI) >
163       BFI.getBlockFreq(L.getLoopPreheader()))
164     BBsToSinkInto.clear();
165   return BBsToSinkInto;
166 }
167 
168 // Sinks \p I from the loop \p L's preheader to its uses. Returns true if
169 // sinking is successful.
170 // \p LoopBlockNumber is used to sort the insertion blocks to ensure
171 // determinism.
172 static bool sinkInstruction(
173     Loop &L, Instruction &I, const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
174     const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber, LoopInfo &LI,
175     DominatorTree &DT, BlockFrequencyInfo &BFI, MemorySSAUpdater *MSSAU) {
176   // Compute the set of blocks in loop L which contain a use of I.
177   SmallPtrSet<BasicBlock *, 2> BBs;
178   for (auto &U : I.uses()) {
179     Instruction *UI = cast<Instruction>(U.getUser());
180 
181     // We cannot sink I if it has uses outside of the loop.
182     if (!L.contains(LI.getLoopFor(UI->getParent())))
183       return false;
184 
185     if (!isa<PHINode>(UI)) {
186       BBs.insert(UI->getParent());
187       continue;
188     }
189 
190     // We cannot sink I to PHI-uses, try to look through PHI to find the incoming
191     // block of the value being used.
192     PHINode *PN = dyn_cast<PHINode>(UI);
193     BasicBlock *PhiBB = PN->getIncomingBlock(U);
194 
195     // If value's incoming block is from loop preheader directly, there's no
196     // place to sink to, bailout.
197     if (L.getLoopPreheader() == PhiBB)
198       return false;
199 
200     BBs.insert(PhiBB);
201   }
202 
203   // findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max
204   // BBs.size() to avoid expensive computation.
205   // FIXME: Handle code size growth for min_size and opt_size.
206   if (BBs.size() > MaxNumberOfUseBBsForSinking)
207     return false;
208 
209   // Find the set of BBs that we should insert a copy of I.
210   SmallPtrSet<BasicBlock *, 2> BBsToSinkInto =
211       findBBsToSinkInto(L, BBs, ColdLoopBBs, DT, BFI);
212   if (BBsToSinkInto.empty())
213     return false;
214 
215   // Return if any of the candidate blocks to sink into is non-cold.
216   if (BBsToSinkInto.size() > 1 &&
217       !llvm::set_is_subset(BBsToSinkInto, LoopBlockNumber))
218     return false;
219 
220   // Copy the final BBs into a vector and sort them using the total ordering
221   // of the loop block numbers as iterating the set doesn't give a useful
222   // order. No need to stable sort as the block numbers are a total ordering.
223   SmallVector<BasicBlock *, 2> SortedBBsToSinkInto;
224   llvm::append_range(SortedBBsToSinkInto, BBsToSinkInto);
225   llvm::sort(SortedBBsToSinkInto, [&](BasicBlock *A, BasicBlock *B) {
226     return LoopBlockNumber.find(A)->second < LoopBlockNumber.find(B)->second;
227   });
228 
229   BasicBlock *MoveBB = *SortedBBsToSinkInto.begin();
230   // FIXME: Optimize the efficiency for cloned value replacement. The current
231   //        implementation is O(SortedBBsToSinkInto.size() * I.num_uses()).
232   for (BasicBlock *N : ArrayRef(SortedBBsToSinkInto).drop_front(1)) {
233     assert(LoopBlockNumber.find(N)->second >
234                LoopBlockNumber.find(MoveBB)->second &&
235            "BBs not sorted!");
236     // Clone I and replace its uses.
237     Instruction *IC = I.clone();
238     IC->setName(I.getName());
239     IC->insertBefore(&*N->getFirstInsertionPt());
240 
241     if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
242       // Create a new MemoryAccess and let MemorySSA set its defining access.
243       MemoryAccess *NewMemAcc =
244           MSSAU->createMemoryAccessInBB(IC, nullptr, N, MemorySSA::Beginning);
245       if (NewMemAcc) {
246         if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
247           MSSAU->insertDef(MemDef, /*RenameUses=*/true);
248         else {
249           auto *MemUse = cast<MemoryUse>(NewMemAcc);
250           MSSAU->insertUse(MemUse, /*RenameUses=*/true);
251         }
252       }
253     }
254 
255     // Replaces uses of I with IC in N
256     I.replaceUsesWithIf(IC, [N](Use &U) {
257       return cast<Instruction>(U.getUser())->getParent() == N;
258     });
259     // Replaces uses of I with IC in blocks dominated by N
260     replaceDominatedUsesWith(&I, IC, DT, N);
261     LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName()
262                       << '\n');
263     NumLoopSunkCloned++;
264   }
265   LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n');
266   NumLoopSunk++;
267   I.moveBefore(&*MoveBB->getFirstInsertionPt());
268 
269   if (MSSAU)
270     if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
271             MSSAU->getMemorySSA()->getMemoryAccess(&I)))
272       MSSAU->moveToPlace(OldMemAcc, MoveBB, MemorySSA::Beginning);
273 
274   return true;
275 }
276 
277 /// Sinks instructions from loop's preheader to the loop body if the
278 /// sum frequency of inserted copy is smaller than preheader's frequency.
279 static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI,
280                                           DominatorTree &DT,
281                                           BlockFrequencyInfo &BFI,
282                                           MemorySSA &MSSA,
283                                           ScalarEvolution *SE) {
284   BasicBlock *Preheader = L.getLoopPreheader();
285   assert(Preheader && "Expected loop to have preheader");
286 
287   assert(Preheader->getParent()->hasProfileData() &&
288          "Unexpected call when profile data unavailable.");
289 
290   const BlockFrequency PreheaderFreq = BFI.getBlockFreq(Preheader);
291   // If there are no basic blocks with lower frequency than the preheader then
292   // we can avoid the detailed analysis as we will never find profitable sinking
293   // opportunities.
294   if (all_of(L.blocks(), [&](const BasicBlock *BB) {
295         return BFI.getBlockFreq(BB) > PreheaderFreq;
296       }))
297     return false;
298 
299   MemorySSAUpdater MSSAU(&MSSA);
300   SinkAndHoistLICMFlags LICMFlags(/*IsSink=*/true, L, MSSA);
301 
302   bool Changed = false;
303 
304   // Sort loop's basic blocks by frequency
305   SmallVector<BasicBlock *, 10> ColdLoopBBs;
306   SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber;
307   int i = 0;
308   for (BasicBlock *B : L.blocks())
309     if (BFI.getBlockFreq(B) < BFI.getBlockFreq(L.getLoopPreheader())) {
310       ColdLoopBBs.push_back(B);
311       LoopBlockNumber[B] = ++i;
312     }
313   llvm::stable_sort(ColdLoopBBs, [&](BasicBlock *A, BasicBlock *B) {
314     return BFI.getBlockFreq(A) < BFI.getBlockFreq(B);
315   });
316 
317   // Traverse preheader's instructions in reverse order because if A depends
318   // on B (A appears after B), A needs to be sunk first before B can be
319   // sinked.
320   for (Instruction &I : llvm::make_early_inc_range(llvm::reverse(*Preheader))) {
321     if (isa<PHINode>(&I))
322       continue;
323     // No need to check for instruction's operands are loop invariant.
324     assert(L.hasLoopInvariantOperands(&I) &&
325            "Insts in a loop's preheader should have loop invariant operands!");
326     if (!canSinkOrHoistInst(I, &AA, &DT, &L, MSSAU, false, LICMFlags))
327       continue;
328     if (sinkInstruction(L, I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI,
329                         &MSSAU)) {
330       Changed = true;
331       if (SE)
332         SE->forgetBlockAndLoopDispositions(&I);
333     }
334   }
335 
336   return Changed;
337 }
338 
339 PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) {
340   // Enable LoopSink only when runtime profile is available.
341   // With static profile, the sinking decision may be sub-optimal.
342   if (!F.hasProfileData())
343     return PreservedAnalyses::all();
344 
345   LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
346   // Nothing to do if there are no loops.
347   if (LI.empty())
348     return PreservedAnalyses::all();
349 
350   AAResults &AA = FAM.getResult<AAManager>(F);
351   DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
352   BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
353   MemorySSA &MSSA = FAM.getResult<MemorySSAAnalysis>(F).getMSSA();
354 
355   // We want to do a postorder walk over the loops. Since loops are a tree this
356   // is equivalent to a reversed preorder walk and preorder is easy to compute
357   // without recursion. Since we reverse the preorder, we will visit siblings
358   // in reverse program order. This isn't expected to matter at all but is more
359   // consistent with sinking algorithms which generally work bottom-up.
360   SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder();
361 
362   bool Changed = false;
363   do {
364     Loop &L = *PreorderLoops.pop_back_val();
365 
366     BasicBlock *Preheader = L.getLoopPreheader();
367     if (!Preheader)
368       continue;
369 
370     // Note that we don't pass SCEV here because it is only used to invalidate
371     // loops in SCEV and we don't preserve (or request) SCEV at all making that
372     // unnecessary.
373     Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI, MSSA,
374                                              /*ScalarEvolution*/ nullptr);
375   } while (!PreorderLoops.empty());
376 
377   if (!Changed)
378     return PreservedAnalyses::all();
379 
380   PreservedAnalyses PA;
381   PA.preserveSet<CFGAnalyses>();
382   PA.preserve<MemorySSAAnalysis>();
383 
384   if (VerifyMemorySSA)
385     MSSA.verifyMemorySSA();
386 
387   return PA;
388 }
389 
390 namespace {
391 struct LegacyLoopSinkPass : public LoopPass {
392   static char ID;
393   LegacyLoopSinkPass() : LoopPass(ID) {
394     initializeLegacyLoopSinkPassPass(*PassRegistry::getPassRegistry());
395   }
396 
397   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
398     if (skipLoop(L))
399       return false;
400 
401     BasicBlock *Preheader = L->getLoopPreheader();
402     if (!Preheader)
403       return false;
404 
405     // Enable LoopSink only when runtime profile is available.
406     // With static profile, the sinking decision may be sub-optimal.
407     if (!Preheader->getParent()->hasProfileData())
408       return false;
409 
410     AAResults &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
411     MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
412     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
413     bool Changed = sinkLoopInvariantInstructions(
414         *L, AA, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
415         getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
416         getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(),
417         MSSA, SE ? &SE->getSE() : nullptr);
418 
419     if (VerifyMemorySSA)
420       MSSA.verifyMemorySSA();
421 
422     return Changed;
423   }
424 
425   void getAnalysisUsage(AnalysisUsage &AU) const override {
426     AU.setPreservesCFG();
427     AU.addRequired<BlockFrequencyInfoWrapperPass>();
428     getLoopAnalysisUsage(AU);
429     AU.addRequired<MemorySSAWrapperPass>();
430     AU.addPreserved<MemorySSAWrapperPass>();
431   }
432 };
433 }
434 
435 char LegacyLoopSinkPass::ID = 0;
436 INITIALIZE_PASS_BEGIN(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false,
437                       false)
438 INITIALIZE_PASS_DEPENDENCY(LoopPass)
439 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
440 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
441 INITIALIZE_PASS_END(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false, false)
442 
443 Pass *llvm::createLoopSinkPass() { return new LegacyLoopSinkPass(); }
444