blob: db502e1c5db89d26d2eff96e9fc0581a3a16546b [file] [log] [blame]
Chandler Carruth1725c8c2017-01-20 08:42:14 +00001//===-- LoopSink.cpp - Loop Sink Pass -------------------------------------===//
Dehao Chenb94c09ba2016-10-27 16:30:08 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass does the inverse transformation of what LICM does.
11// It traverses all of the instructions in the loop's preheader and sinks
12// them to the loop body where frequency is lower than the loop's preheader.
13// This pass is a reverse-transformation of LICM. It differs from the Sink
14// pass in the following ways:
15//
16// * It only handles sinking of instructions from the loop's preheader to the
17// loop's body
18// * It uses alias set tracker to get more accurate alias info
19// * It uses block frequency info to find the optimal sinking locations
20//
21// Overall algorithm:
22//
23// For I in Preheader:
24// InsertBBs = BBs that uses I
25// For BB in sorted(LoopBBs):
26// DomBBs = BBs in InsertBBs that are dominated by BB
27// if freq(DomBBs) > freq(BB)
28// InsertBBs = UseBBs - DomBBs + BB
29// For BB in InsertBBs:
30// Insert I at BB's beginning
Chandler Carruth1725c8c2017-01-20 08:42:14 +000031//
Dehao Chenb94c09ba2016-10-27 16:30:08 +000032//===----------------------------------------------------------------------===//
33
Chandler Carruthe9b18e32017-01-20 08:42:19 +000034#include "llvm/Transforms/Scalar/LoopSink.h"
Dehao Chenb94c09ba2016-10-27 16:30:08 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/Analysis/AliasSetTracker.h"
38#include "llvm/Analysis/BasicAliasAnalysis.h"
39#include "llvm/Analysis/BlockFrequencyInfo.h"
40#include "llvm/Analysis/Loads.h"
41#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/LoopPass.h"
Dehao Chenb94c09ba2016-10-27 16:30:08 +000043#include "llvm/Analysis/ScalarEvolution.h"
44#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
David Blaikie31b98d22018-06-04 21:23:21 +000045#include "llvm/Transforms/Utils/Local.h"
Dehao Chenb94c09ba2016-10-27 16:30:08 +000046#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Instructions.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Metadata.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000052#include "llvm/Transforms/Scalar/LoopPassManager.h"
Dehao Chenb94c09ba2016-10-27 16:30:08 +000053#include "llvm/Transforms/Utils/LoopUtils.h"
54using namespace llvm;
55
56#define DEBUG_TYPE "loopsink"
57
58STATISTIC(NumLoopSunk, "Number of instructions sunk into loop");
59STATISTIC(NumLoopSunkCloned, "Number of cloned instructions sunk into loop");
60
61static cl::opt<unsigned> SinkFrequencyPercentThreshold(
62 "sink-freq-percent-threshold", cl::Hidden, cl::init(90),
63 cl::desc("Do not sink instructions that require cloning unless they "
64 "execute less than this percent of the time."));
65
66static cl::opt<unsigned> MaxNumberOfUseBBsForSinking(
67 "max-uses-for-sinking", cl::Hidden, cl::init(30),
68 cl::desc("Do not sink instructions that have too many uses."));
69
70/// Return adjusted total frequency of \p BBs.
71///
72/// * If there is only one BB, sinking instruction will not introduce code
73/// size increase. Thus there is no need to adjust the frequency.
74/// * If there are more than one BB, sinking would lead to code size increase.
75/// In this case, we add some "tax" to the total frequency to make it harder
76/// to sink. E.g.
77/// Freq(Preheader) = 100
78/// Freq(BBs) = sum(50, 49) = 99
79/// Even if Freq(BBs) < Freq(Preheader), we will not sink from Preheade to
80/// BBs as the difference is too small to justify the code size increase.
81/// To model this, The adjusted Freq(BBs) will be:
82/// AdjustedFreq(BBs) = 99 / SinkFrequencyPercentThreshold%
83static BlockFrequency adjustedSumFreq(SmallPtrSetImpl<BasicBlock *> &BBs,
84 BlockFrequencyInfo &BFI) {
85 BlockFrequency T = 0;
86 for (BasicBlock *B : BBs)
87 T += BFI.getBlockFreq(B);
88 if (BBs.size() > 1)
89 T /= BranchProbability(SinkFrequencyPercentThreshold, 100);
90 return T;
91}
92
93/// Return a set of basic blocks to insert sinked instructions.
94///
95/// The returned set of basic blocks (BBsToSinkInto) should satisfy:
96///
97/// * Inside the loop \p L
98/// * For each UseBB in \p UseBBs, there is at least one BB in BBsToSinkInto
99/// that domintates the UseBB
100/// * Has minimum total frequency that is no greater than preheader frequency
101///
102/// The purpose of the function is to find the optimal sinking points to
103/// minimize execution cost, which is defined as "sum of frequency of
104/// BBsToSinkInto".
105/// As a result, the returned BBsToSinkInto needs to have minimum total
106/// frequency.
107/// Additionally, if the total frequency of BBsToSinkInto exceeds preheader
108/// frequency, the optimal solution is not sinking (return empty set).
109///
110/// \p ColdLoopBBs is used to help find the optimal sinking locations.
111/// It stores a list of BBs that is:
112///
113/// * Inside the loop \p L
114/// * Has a frequency no larger than the loop's preheader
115/// * Sorted by BB frequency
116///
117/// The complexity of the function is O(UseBBs.size() * ColdLoopBBs.size()).
118/// To avoid expensive computation, we cap the maximum UseBBs.size() in its
119/// caller.
120static SmallPtrSet<BasicBlock *, 2>
121findBBsToSinkInto(const Loop &L, const SmallPtrSetImpl<BasicBlock *> &UseBBs,
122 const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
123 DominatorTree &DT, BlockFrequencyInfo &BFI) {
124 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto;
125 if (UseBBs.size() == 0)
126 return BBsToSinkInto;
127
128 BBsToSinkInto.insert(UseBBs.begin(), UseBBs.end());
129 SmallPtrSet<BasicBlock *, 2> BBsDominatedByColdestBB;
130
131 // For every iteration:
132 // * Pick the ColdestBB from ColdLoopBBs
133 // * Find the set BBsDominatedByColdestBB that satisfy:
134 // - BBsDominatedByColdestBB is a subset of BBsToSinkInto
135 // - Every BB in BBsDominatedByColdestBB is dominated by ColdestBB
136 // * If Freq(ColdestBB) < Freq(BBsDominatedByColdestBB), remove
137 // BBsDominatedByColdestBB from BBsToSinkInto, add ColdestBB to
138 // BBsToSinkInto
139 for (BasicBlock *ColdestBB : ColdLoopBBs) {
140 BBsDominatedByColdestBB.clear();
141 for (BasicBlock *SinkedBB : BBsToSinkInto)
142 if (DT.dominates(ColdestBB, SinkedBB))
143 BBsDominatedByColdestBB.insert(SinkedBB);
144 if (BBsDominatedByColdestBB.size() == 0)
145 continue;
146 if (adjustedSumFreq(BBsDominatedByColdestBB, BFI) >
147 BFI.getBlockFreq(ColdestBB)) {
148 for (BasicBlock *DominatedBB : BBsDominatedByColdestBB) {
149 BBsToSinkInto.erase(DominatedBB);
150 }
151 BBsToSinkInto.insert(ColdestBB);
152 }
153 }
154
Hans Wennborge0f3e922018-08-29 06:55:27 +0000155 // Can't sink into blocks that have no valid insertion point.
156 for (BasicBlock *BB : BBsToSinkInto) {
157 if (BB->getFirstInsertionPt() == BB->end()) {
158 BBsToSinkInto.clear();
159 break;
160 }
161 }
162
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000163 // If the total frequency of BBsToSinkInto is larger than preheader frequency,
164 // do not sink.
165 if (adjustedSumFreq(BBsToSinkInto, BFI) >
166 BFI.getBlockFreq(L.getLoopPreheader()))
167 BBsToSinkInto.clear();
168 return BBsToSinkInto;
169}
170
171// Sinks \p I from the loop \p L's preheader to its uses. Returns true if
172// sinking is successful.
173// \p LoopBlockNumber is used to sort the insertion blocks to ensure
174// determinism.
175static bool sinkInstruction(Loop &L, Instruction &I,
176 const SmallVectorImpl<BasicBlock *> &ColdLoopBBs,
177 const SmallDenseMap<BasicBlock *, int, 16> &LoopBlockNumber,
178 LoopInfo &LI, DominatorTree &DT,
179 BlockFrequencyInfo &BFI) {
180 // Compute the set of blocks in loop L which contain a use of I.
181 SmallPtrSet<BasicBlock *, 2> BBs;
182 for (auto &U : I.uses()) {
183 Instruction *UI = cast<Instruction>(U.getUser());
184 // We cannot sink I to PHI-uses.
185 if (dyn_cast<PHINode>(UI))
186 return false;
187 // We cannot sink I if it has uses outside of the loop.
188 if (!L.contains(LI.getLoopFor(UI->getParent())))
189 return false;
190 BBs.insert(UI->getParent());
191 }
192
193 // findBBsToSinkInto is O(BBs.size() * ColdLoopBBs.size()). We cap the max
194 // BBs.size() to avoid expensive computation.
195 // FIXME: Handle code size growth for min_size and opt_size.
196 if (BBs.size() > MaxNumberOfUseBBsForSinking)
197 return false;
198
199 // Find the set of BBs that we should insert a copy of I.
200 SmallPtrSet<BasicBlock *, 2> BBsToSinkInto =
201 findBBsToSinkInto(L, BBs, ColdLoopBBs, DT, BFI);
202 if (BBsToSinkInto.empty())
203 return false;
204
205 // Copy the final BBs into a vector and sort them using the total ordering
206 // of the loop block numbers as iterating the set doesn't give a useful
207 // order. No need to stable sort as the block numbers are a total ordering.
208 SmallVector<BasicBlock *, 2> SortedBBsToSinkInto;
209 SortedBBsToSinkInto.insert(SortedBBsToSinkInto.begin(), BBsToSinkInto.begin(),
210 BBsToSinkInto.end());
Fangrui Song0cac7262018-09-27 02:13:45 +0000211 llvm::sort(SortedBBsToSinkInto, [&](BasicBlock *A, BasicBlock *B) {
212 return LoopBlockNumber.find(A)->second < LoopBlockNumber.find(B)->second;
213 });
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000214
215 BasicBlock *MoveBB = *SortedBBsToSinkInto.begin();
216 // FIXME: Optimize the efficiency for cloned value replacement. The current
217 // implementation is O(SortedBBsToSinkInto.size() * I.num_uses()).
Benjamin Kramer3687ac522018-07-06 14:20:58 +0000218 for (BasicBlock *N : makeArrayRef(SortedBBsToSinkInto).drop_front(1)) {
219 assert(LoopBlockNumber.find(N)->second >
220 LoopBlockNumber.find(MoveBB)->second &&
221 "BBs not sorted!");
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000222 // Clone I and replace its uses.
223 Instruction *IC = I.clone();
224 IC->setName(I.getName());
225 IC->insertBefore(&*N->getFirstInsertionPt());
226 // Replaces uses of I with IC in N
227 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
228 Use &U = *UI++;
229 auto *I = cast<Instruction>(U.getUser());
230 if (I->getParent() == N)
231 U.set(IC);
232 }
233 // Replaces uses of I with IC in blocks dominated by N
234 replaceDominatedUsesWith(&I, IC, DT, N);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000235 LLVM_DEBUG(dbgs() << "Sinking a clone of " << I << " To: " << N->getName()
236 << '\n');
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000237 NumLoopSunkCloned++;
238 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000239 LLVM_DEBUG(dbgs() << "Sinking " << I << " To: " << MoveBB->getName() << '\n');
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000240 NumLoopSunk++;
241 I.moveBefore(&*MoveBB->getFirstInsertionPt());
242
243 return true;
244}
245
246/// Sinks instructions from loop's preheader to the loop body if the
247/// sum frequency of inserted copy is smaller than preheader's frequency.
248static bool sinkLoopInvariantInstructions(Loop &L, AAResults &AA, LoopInfo &LI,
249 DominatorTree &DT,
250 BlockFrequencyInfo &BFI,
251 ScalarEvolution *SE) {
252 BasicBlock *Preheader = L.getLoopPreheader();
253 if (!Preheader)
254 return false;
255
Dehao Chen947dbe122016-11-09 00:58:19 +0000256 // Enable LoopSink only when runtime profile is available.
257 // With static profile, the sinking decision may be sub-optimal.
Easwaran Ramana17f2202017-12-22 01:33:52 +0000258 if (!Preheader->getParent()->hasProfileData())
Dehao Chen947dbe122016-11-09 00:58:19 +0000259 return false;
260
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000261 const BlockFrequency PreheaderFreq = BFI.getBlockFreq(Preheader);
262 // If there are no basic blocks with lower frequency than the preheader then
263 // we can avoid the detailed analysis as we will never find profitable sinking
264 // opportunities.
265 if (all_of(L.blocks(), [&](const BasicBlock *BB) {
266 return BFI.getBlockFreq(BB) > PreheaderFreq;
267 }))
268 return false;
269
270 bool Changed = false;
271 AliasSetTracker CurAST(AA);
272
273 // Compute alias set.
274 for (BasicBlock *BB : L.blocks())
275 CurAST.add(*BB);
276
277 // Sort loop's basic blocks by frequency
278 SmallVector<BasicBlock *, 10> ColdLoopBBs;
279 SmallDenseMap<BasicBlock *, int, 16> LoopBlockNumber;
280 int i = 0;
281 for (BasicBlock *B : L.blocks())
282 if (BFI.getBlockFreq(B) < BFI.getBlockFreq(L.getLoopPreheader())) {
283 ColdLoopBBs.push_back(B);
284 LoopBlockNumber[B] = ++i;
285 }
286 std::stable_sort(ColdLoopBBs.begin(), ColdLoopBBs.end(),
287 [&](BasicBlock *A, BasicBlock *B) {
288 return BFI.getBlockFreq(A) < BFI.getBlockFreq(B);
289 });
290
291 // Traverse preheader's instructions in reverse order becaue if A depends
292 // on B (A appears after B), A needs to be sinked first before B can be
293 // sinked.
294 for (auto II = Preheader->rbegin(), E = Preheader->rend(); II != E;) {
295 Instruction *I = &*II++;
Xin Tong12c8cb32017-01-10 00:39:49 +0000296 // No need to check for instruction's operands are loop invariant.
297 assert(L.hasLoopInvariantOperands(I) &&
298 "Insts in a loop's preheader should have loop invariant operands!");
Philip Reames32cb80b2018-08-02 04:08:04 +0000299 if (!canSinkOrHoistInst(*I, &AA, &DT, &L, &CurAST, false))
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000300 continue;
301 if (sinkInstruction(L, *I, ColdLoopBBs, LoopBlockNumber, LI, DT, BFI))
302 Changed = true;
303 }
304
305 if (Changed && SE)
306 SE->forgetLoopDispositions(&L);
307 return Changed;
308}
309
Chandler Carruthe9b18e32017-01-20 08:42:19 +0000310PreservedAnalyses LoopSinkPass::run(Function &F, FunctionAnalysisManager &FAM) {
311 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
312 // Nothing to do if there are no loops.
313 if (LI.empty())
314 return PreservedAnalyses::all();
315
316 AAResults &AA = FAM.getResult<AAManager>(F);
317 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
318 BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
319
320 // We want to do a postorder walk over the loops. Since loops are a tree this
321 // is equivalent to a reversed preorder walk and preorder is easy to compute
322 // without recursion. Since we reverse the preorder, we will visit siblings
323 // in reverse program order. This isn't expected to matter at all but is more
324 // consistent with sinking algorithms which generally work bottom-up.
325 SmallVector<Loop *, 4> PreorderLoops = LI.getLoopsInPreorder();
326
327 bool Changed = false;
328 do {
329 Loop &L = *PreorderLoops.pop_back_val();
330
331 // Note that we don't pass SCEV here because it is only used to invalidate
332 // loops in SCEV and we don't preserve (or request) SCEV at all making that
333 // unnecessary.
334 Changed |= sinkLoopInvariantInstructions(L, AA, LI, DT, BFI,
335 /*ScalarEvolution*/ nullptr);
336 } while (!PreorderLoops.empty());
337
338 if (!Changed)
339 return PreservedAnalyses::all();
340
341 PreservedAnalyses PA;
342 PA.preserveSet<CFGAnalyses>();
343 return PA;
344}
345
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000346namespace {
347struct LegacyLoopSinkPass : public LoopPass {
348 static char ID;
349 LegacyLoopSinkPass() : LoopPass(ID) {
350 initializeLegacyLoopSinkPassPass(*PassRegistry::getPassRegistry());
351 }
352
353 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
354 if (skipLoop(L))
355 return false;
356
357 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
358 return sinkLoopInvariantInstructions(
359 *L, getAnalysis<AAResultsWrapperPass>().getAAResults(),
360 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
361 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
362 getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(),
363 SE ? &SE->getSE() : nullptr);
364 }
365
366 void getAnalysisUsage(AnalysisUsage &AU) const override {
367 AU.setPreservesCFG();
368 AU.addRequired<BlockFrequencyInfoWrapperPass>();
369 getLoopAnalysisUsage(AU);
370 }
371};
372}
373
374char LegacyLoopSinkPass::ID = 0;
375INITIALIZE_PASS_BEGIN(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false,
376 false)
377INITIALIZE_PASS_DEPENDENCY(LoopPass)
378INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
379INITIALIZE_PASS_END(LegacyLoopSinkPass, "loop-sink", "Loop Sink", false, false)
380
381Pass *llvm::createLoopSinkPass() { return new LegacyLoopSinkPass(); }