LoopSink.cpp 18 KB

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