LoopSink.cpp 16 KB

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