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 "ScalarOptions.h"
35#include "llvm/ADT/SetOperations.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/Analysis/AliasAnalysis.h"
38#include "llvm/Analysis/BlockFrequencyInfo.h"
39#include "llvm/Analysis/LoopInfo.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/Support/BranchProbability.h"
46#include "llvm/Transforms/Scalar.h"
47#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Transforms/Utils/LoopUtils.h"
49using namespace llvm;
50
51#define DEBUG_TYPE "loopsink"
52
53STATISTIC(NumLoopSunk, "Number of instructions sunk into loop");
54STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop");
55
56/// Return adjusted total frequency of \p BBs.
57///
58/// * If there is only one BB, sinking instruction will not introduce code
59/// size increase. Thus there is no need to adjust the frequency.
60/// * If there are more than one BB, sinking would lead to code size increase.
61/// In this case, we add some "tax" to the total frequency to make it harder
62/// to sink. E.g.
63/// Freq(Preheader) = 100
64/// Freq(BBs) = sum(50, 49) = 99
65/// Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to
66/// BBs as the difference is too small to justify the code size increase.
67/// To model this, The adjusted Freq(BBs) will be:
68/// AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold%
69static BlockFrequency adjustedSumFreq(const ScalarOptions &Opts,
70 SmallPtrSetImpl<BasicBlock *> &BBs,
71 BlockFrequencyInfo &BFI) {
72 BlockFrequency T(0);
73 for (BasicBlock *B : BBs)
74 T += BFI.getBlockFreq(BB: B);
75 if (BBs.size() > 1)
76 T /= BranchProbability(Opts.sink_freq_percent_threshold, 100);
77 return T;
78}
79
80/// Return a set of basic blocks to insert sinked instructions.
81///
82/// The returned set of basic blocks (BBsToSinkInto) should satisfy:
83///
84/// * Inside the loop \p L
85/// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto
86/// that domintates the UseBB
87/// * Has minimum total frequency that is no greater than preheader frequency
88///
89/// The purpose of the function is to find the optimal sinking points to
90/// minimize execution cost, which is defined as "sum of frequency of
91/// BBsToSinkInto".
92/// As a result, the returned BBsToSinkInto needs to have minimum total
93/// frequency.
94/// Additionally, if the total frequency of BBsToSinkInto exceeds preheader
95/// frequency, the optimal solution is not sinking (return empty set).
96///
97/// \p ColdLoopBBs is used to help find the optimal sinking locations.
98/// It stores a list of BBs that is:
99///
100/// * Inside the loop \p L
101/// * Has a frequency no larger than the loop's preheader
102/// * Sorted by BB frequency
103///
104/// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()).
105/// To avoid expensive computation, we cap the maximum UseBBs.size() in its
106/// caller.
107static SmallPtrSet<BasicBlock *, 2>
108findBBsToSinkInto(const ScalarOptions &Opts, const Loop &L,
109 const SmallPtrSetImpl<BasicBlock *> &UseBBs,
110 const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
111 DominatorTree &DT, BlockFrequencyInfo &BFI) {
112 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto;
113 if (UseBBs.size() == 0)
114 return BBsToSinkInto;
115
116 BBsToSinkInto.insert_range(R: UseBBs);
117 SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB;
118
119 // For every iteration:
120 // * Pick the ColdestBB from ColdLoopBBs
121 // * Find the set BBsDominatedByColdestBB that satisfy:
122 // - BBsDominatedByColdestBB is a subset of BBsToSinkInto
123 // - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB
124 // * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove
125 // BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to
126 // BBsToSinkInto
127 for (BasicBlock *ColdestBB : ColdLoopBBs) {
128 BBsDominatedByColdestBB.clear();
129 for (BasicBlock *SinkedBB : BBsToSinkInto)
130 if (DT.dominates(A: ColdestBB, B: SinkedBB))
131 BBsDominatedByColdestBB.insert(Ptr: SinkedBB);
132 if (BBsDominatedByColdestBB.size() == 0)
133 continue;
134 if (adjustedSumFreq(Opts, BBs&: BBsDominatedByColdestBB, BFI) >
135 BFI.getBlockFreq(BB: ColdestBB)) {
136 for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) {
137 BBsToSinkInto.erase(Ptr: DominatedBB);
138 }
139 BBsToSinkInto.insert(Ptr: ColdestBB);
140 continue;
141 }
142 // Otherwise, see if we can stop the search through the cold BBs early.
143 // Since the ColdLoopBBs list is sorted in increasing magnitude of
144 // frequency the cold BB frequencies can only get larger. The
145 // BBsToSinkInto set can only get smaller and have a smaller
146 // adjustedSumFreq, due to the earlier checking. So once we find a cold BB
147 // with a frequency at least as large as the adjustedSumFreq of the
148 // current BBsToSinkInto set, the earlier frequency check can never be
149 // true for a future iteration. Note we could do check this more
150 // aggressively earlier, but in practice this ended up being more
151 // expensive overall (added checking to the critical path through the loop
152 // that often ended up continuing early due to an empty
153 // BBsDominatedByColdestBB set, and the frequency check there was false
154 // most of the time anyway).
155 if (adjustedSumFreq(Opts, BBs&: BBsToSinkInto, BFI) <=
156 BFI.getBlockFreq(BB: ColdestBB))
157 break;
158 }
159
160 // Can't sink into blocks that have no valid insertion point.
161 for (BasicBlock *BB : BBsToSinkInto) {
162 if (BB->getFirstInsertionPt() == BB->end()) {
163 BBsToSinkInto.clear();
164 break;
165 }
166 }
167
168 // If the total frequency of BBsToSinkInto is larger than preheader frequency,
169 // do not sink.
170 if (adjustedSumFreq(Opts, BBs&: BBsToSinkInto, BFI) >
171 BFI.getBlockFreq(BB: L.getLoopPreheader()))
172 BBsToSinkInto.clear();
173 return BBsToSinkInto;
174}
175
176// Sinks \p I from the loop \p L's preheader to its uses. Returns true if
177// sinking is successful.
178// \p LoopBlockNumber is used to sort the insertion blocks to ensure
179// determinism.
180static bool
181sinkInstruction(const ScalarOptions &Opts, Loop &L, Instruction &I,
182 const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
183 const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber,
184 LoopInfo &LI, DominatorTree &DT, BlockFrequencyInfo &BFI,
185 MemorySSAUpdater *MSSAU) {
186 // Compute the set of blocks in loop L which contain a use of I.
187 SmallPtrSet<BasicBlock *, 2> BBs;
188 for (auto &U : I.uses()) {
189 Instruction *UI = cast<Instruction>(Val: U.getUser());
190
191 // We cannot sink I if it has uses outside of the loop.
192 if (!L.contains(L: LI.getLoopFor(BB: UI->getParent())))
193 return false;
194
195 if (!isa<PHINode>(Val: UI)) {
196 BBs.insert(Ptr: UI->getParent());
197 continue;
198 }
199
200 // We cannot sink I to PHI-uses, try to look through PHI to find the incoming
201 // block of the value being used.
202 PHINode *PN = dyn_cast<PHINode>(Val: UI);
203 BasicBlock *PhiBB = PN->getIncomingBlock(U);
204
205 // If value's incoming block is from loop preheader directly, there's no
206 // place to sink to, bailout.
207 if (L.getLoopPreheader() == PhiBB)
208 return false;
209
210 BBs.insert(Ptr: PhiBB);
211 }
212
213 // findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max
214 // BBs.size() to avoid expensive computation.
215 // FIXME: Handle code size growth for min_size and opt_size.
216 if (BBs.size() > Opts.max_uses_for_sinking)
217 return false;
218
219 // Find the set of BBs that we should insert a copy of I.
220 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto =
221 findBBsToSinkInto(Opts, L, UseBBs: BBs, ColdLoopBBs, DT, BFI);
222 if (BBsToSinkInto.empty())
223 return false;
224
225 // Return if any of the candidate blocks to sink into is non-cold.
226 if (BBsToSinkInto.size() > 1 &&
227 !llvm::set_is_subset(S1: BBsToSinkInto, S2: LoopBlockNumber))
228 return false;
229
230 // Copy the final BBs into a vector and sort them using the total ordering
231 // of the loop block numbers as iterating the set doesn't give a useful
232 // order. No need to stable sort as the block numbers are a total ordering.
233 SmallVector<BasicBlock *, 2> SortedBBsToSinkInto;
234 llvm::append_range(C&: SortedBBsToSinkInto, R&: BBsToSinkInto);
235 if (SortedBBsToSinkInto.size() > 1) {
236 llvm::sort(C&: SortedBBsToSinkInto, Comp: [&](BasicBlock *A, BasicBlock *B) {
237 return LoopBlockNumber.find(Val: A)->second < LoopBlockNumber.find(Val: B)->second;
238 });
239 }
240
241 BasicBlock *MoveBB = *SortedBBsToSinkInto.begin();
242 // FIXME: Optimize the efficiency for cloned value replacement. The current
243 // implementation is O(SortedBBsToSinkInto.size() * I.num_uses()).
244 for (BasicBlock *N : ArrayRef(SortedBBsToSinkInto).drop_front(N: 1)) {
245 assert(LoopBlockNumber.find(N)->second >
246 LoopBlockNumber.find(MoveBB)->second &&
247 "BBs not sorted!");
248 // Clone I and replace its uses.
249 Instruction *IC = I.clone();
250 IC->setName(I.getName());
251 IC->insertBefore(InsertPos: N->getFirstInsertionPt());
252
253 if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(I: &I)) {
254 // Create a new MemoryAccess and let MemorySSA set its defining access.
255 MemoryAccess *NewMemAcc =
256 MSSAU->createMemoryAccessInBB(I: IC, Definition: nullptr, BB: N, Point: MemorySSA::Beginning);
257 if (NewMemAcc) {
258 if (auto *MemDef = dyn_cast<MemoryDef>(Val: NewMemAcc))
259 MSSAU->insertDef(Def: MemDef, /*RenameUses=*/true);
260 else {
261 auto *MemUse = cast<MemoryUse>(Val: NewMemAcc);
262 MSSAU->insertUse(Use: MemUse, /*RenameUses=*/true);
263 }
264 }
265 }
266
267 // Replaces uses of I with IC in N, except PHI-use which is being taken
268 // care of by defs in PHI's incoming blocks.
269 I.replaceUsesWithIf(New: IC, ShouldReplace: [N](Use &U) {
270 Instruction *UIToReplace = cast<Instruction>(Val: U.getUser());
271 return UIToReplace->getParent() == N && !isa<PHINode>(Val: UIToReplace);
272 });
273 // Replaces uses of I with IC in blocks dominated by N
274 replaceDominatedUsesWith(From: &I, To: IC, DT, BB: N);
275 LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName()
276 << '\n');
277 NumLoopSunkCloned++;
278 }
279 LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n');
280 NumLoopSunk++;
281 I.moveBefore(InsertPos: MoveBB->getFirstInsertionPt());
282
283 if (MSSAU)
284 if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
285 Val: MSSAU->getMemorySSA()->getMemoryAccess(I: &I)))
286 MSSAU->moveToPlace(What: OldMemAcc, BB: MoveBB, Where: MemorySSA::Beginning);
287
288 return true;
289}
290
291/// Sinks instructions from loop's preheader to the loop body if the
292/// sum frequency of inserted copy is smaller than preheader's frequency.
293static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI,
294 DominatorTree &DT,
295 BlockFrequencyInfo &BFI,
296 MemorySSA &MSSA,
297 ScalarEvolution *SE) {
298 const ScalarOptions &Opts = ScalarOptions::Global;
299 BasicBlock *Preheader = L.getLoopPreheader();
300 assert(Preheader && "Expected loop to have preheader");
301
302 assert(Preheader->getParent()->hasProfileData() &&
303 "Unexpected call when profile data unavailable.");
304
305 const BlockFrequency PreheaderFreq = BFI.getBlockFreq(BB: Preheader);
306 // If there are no basic blocks with lower frequency than the preheader then
307 // we can avoid the detailed analysis as we will never find profitable sinking
308 // opportunities.
309 if (all_of(Range: L.blocks(), P: [&](const BasicBlock *BB) {
310 return BFI.getBlockFreq(BB) > PreheaderFreq;
311 }))
312 return false;
313
314 MemorySSAUpdater MSSAU(&MSSA);
315 SinkAndHoistLICMFlags LICMFlags(/*IsSink=*/true, L, MSSA);
316
317 bool Changed = false;
318
319 // Sort loop's basic blocks by frequency
320 SmallVector<BasicBlock *, 10> ColdLoopBBs;
321 SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber;
322 int i = 0;
323 for (BasicBlock *B : L.blocks())
324 if (BFI.getBlockFreq(BB: B) < BFI.getBlockFreq(BB: L.getLoopPreheader())) {
325 ColdLoopBBs.push_back(Elt: B);
326 LoopBlockNumber[B] = ++i;
327 }
328 llvm::stable_sort(Range&: ColdLoopBBs, C: [&](BasicBlock *A, BasicBlock *B) {
329 return BFI.getBlockFreq(BB: A) < BFI.getBlockFreq(BB: B);
330 });
331
332 // Traverse preheader's instructions in reverse order because if A depends
333 // on B (A appears after B), A needs to be sunk first before B can be
334 // sinked.
335 for (Instruction &I : llvm::make_early_inc_range(Range: llvm::reverse(C&: *Preheader))) {
336 if (isa<PHINode>(Val: &I))
337 continue;
338 // No need to check for instruction's operands are loop invariant.
339 assert(L.hasLoopInvariantOperands(&I) &&
340 "Insts in a loop's preheader should have loop invariant operands!");
341 if (!canSinkOrHoistInst(I, AA: &AA, DT: &DT, CurLoop: &L, MSSAU, TargetExecutesOncePerLoop: false, LICMFlags))
342 continue;
343 if (sinkInstruction(Opts, L, I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI,
344 MSSAU: &MSSAU)) {
345 Changed = true;
346 if (SE)
347 SE->forgetBlockAndLoopDispositions(V: &I);
348 }
349 }
350
351 return Changed;
352}
353
354PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) {
355 // Enable LoopSink only when runtime profile is available.
356 // With static profile, the sinking decision may be sub-optimal.
357 if (!F.hasProfileData())
358 return PreservedAnalyses::all();
359
360 LoopInfo &LI = FAM.getResult<LoopAnalysis>(IR&: F);
361 // Nothing to do if there are no loops.
362 if (LI.empty())
363 return PreservedAnalyses::all();
364
365 AAResults &AA = FAM.getResult<AAManager>(IR&: F);
366 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(IR&: F);
367 BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(IR&: F);
368 MemorySSA &MSSA = FAM.getResult<MemorySSAAnalysis>(IR&: F).getMSSA();
369
370 // We want to do a postorder walk over the loops. Since loops are a tree this
371 // is equivalent to a reversed preorder walk and preorder is easy to compute
372 // without recursion. Since we reverse the preorder, we will visit siblings
373 // in reverse program order. This isn't expected to matter at all but is more
374 // consistent with sinking algorithms which generally work bottom-up.
375 SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder();
376
377 bool Changed = false;
378 do {
379 Loop &L = *PreorderLoops.pop_back_val();
380
381 BasicBlock *Preheader = L.getLoopPreheader();
382 if (!Preheader)
383 continue;
384
385 // Note that we don't pass SCEV here because it is only used to invalidate
386 // loops in SCEV and we don't preserve (or request) SCEV at all making that
387 // unnecessary.
388 Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI, MSSA,
389 /*ScalarEvolution*/ SE: nullptr);
390 } while (!PreorderLoops.empty());
391
392 if (!Changed)
393 return PreservedAnalyses::all();
394
395 PreservedAnalyses PA;
396 PA.preserveSet<CFGAnalyses>();
397 PA.preserve<MemorySSAAnalysis>();
398
399 if (VerifyMemorySSA)
400 MSSA.verifyMemorySSA();
401
402 return PA;
403}
404