BreakCriticalEdges.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. //===- BreakCriticalEdges.cpp - Critical Edge Elimination 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. // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
  10. // inserting a dummy basic block. This pass may be "required" by passes that
  11. // cannot deal with critical edges. For this usage, the structure type is
  12. // forward declared. This pass obviously invalidates the CFG, but can update
  13. // dominator trees.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
  17. #include "llvm/ADT/SetVector.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/BlockFrequencyInfo.h"
  21. #include "llvm/Analysis/BranchProbabilityInfo.h"
  22. #include "llvm/Analysis/CFG.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/MemorySSAUpdater.h"
  25. #include "llvm/Analysis/PostDominators.h"
  26. #include "llvm/IR/CFG.h"
  27. #include "llvm/IR/Dominators.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/InitializePasses.h"
  30. #include "llvm/Transforms/Utils.h"
  31. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  32. #include "llvm/Transforms/Utils/Cloning.h"
  33. #include "llvm/Transforms/Utils/ValueMapper.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "break-crit-edges"
  36. STATISTIC(NumBroken, "Number of blocks inserted");
  37. namespace {
  38. struct BreakCriticalEdges : public FunctionPass {
  39. static char ID; // Pass identification, replacement for typeid
  40. BreakCriticalEdges() : FunctionPass(ID) {
  41. initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
  42. }
  43. bool runOnFunction(Function &F) override {
  44. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  45. auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  46. auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
  47. auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
  48. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  49. auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  50. unsigned N =
  51. SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI, nullptr, PDT));
  52. NumBroken += N;
  53. return N > 0;
  54. }
  55. void getAnalysisUsage(AnalysisUsage &AU) const override {
  56. AU.addPreserved<DominatorTreeWrapperPass>();
  57. AU.addPreserved<LoopInfoWrapperPass>();
  58. // No loop canonicalization guarantees are broken by this pass.
  59. AU.addPreservedID(LoopSimplifyID);
  60. }
  61. };
  62. }
  63. char BreakCriticalEdges::ID = 0;
  64. INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
  65. "Break critical edges in CFG", false, false)
  66. // Publicly exposed interface to pass...
  67. char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
  68. FunctionPass *llvm::createBreakCriticalEdgesPass() {
  69. return new BreakCriticalEdges();
  70. }
  71. PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
  72. FunctionAnalysisManager &AM) {
  73. auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
  74. auto *LI = AM.getCachedResult<LoopAnalysis>(F);
  75. unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
  76. NumBroken += N;
  77. if (N == 0)
  78. return PreservedAnalyses::all();
  79. PreservedAnalyses PA;
  80. PA.preserve<DominatorTreeAnalysis>();
  81. PA.preserve<LoopAnalysis>();
  82. return PA;
  83. }
  84. //===----------------------------------------------------------------------===//
  85. // Implementation of the external critical edge manipulation functions
  86. //===----------------------------------------------------------------------===//
  87. BasicBlock *llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
  88. const CriticalEdgeSplittingOptions &Options,
  89. const Twine &BBName) {
  90. if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
  91. return nullptr;
  92. return SplitKnownCriticalEdge(TI, SuccNum, Options, BBName);
  93. }
  94. BasicBlock *
  95. llvm::SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
  96. const CriticalEdgeSplittingOptions &Options,
  97. const Twine &BBName) {
  98. assert(!isa<IndirectBrInst>(TI) &&
  99. "Cannot split critical edge from IndirectBrInst");
  100. BasicBlock *TIBB = TI->getParent();
  101. BasicBlock *DestBB = TI->getSuccessor(SuccNum);
  102. // Splitting the critical edge to a pad block is non-trivial. Don't do
  103. // it in this generic function.
  104. if (DestBB->isEHPad()) return nullptr;
  105. if (Options.IgnoreUnreachableDests &&
  106. isa<UnreachableInst>(DestBB->getFirstNonPHIOrDbgOrLifetime()))
  107. return nullptr;
  108. auto *LI = Options.LI;
  109. SmallVector<BasicBlock *, 4> LoopPreds;
  110. // Check if extra modifications will be required to preserve loop-simplify
  111. // form after splitting. If it would require splitting blocks with IndirectBr
  112. // terminators, bail out if preserving loop-simplify form is requested.
  113. if (LI) {
  114. if (Loop *TIL = LI->getLoopFor(TIBB)) {
  115. // The only way that we can break LoopSimplify form by splitting a
  116. // critical edge is if after the split there exists some edge from TIL to
  117. // DestBB *and* the only edge into DestBB from outside of TIL is that of
  118. // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
  119. // is the new exit block and it has no non-loop predecessors. If the
  120. // second isn't true, then DestBB was not in LoopSimplify form prior to
  121. // the split as it had a non-loop predecessor. In both of these cases,
  122. // the predecessor must be directly in TIL, not in a subloop, or again
  123. // LoopSimplify doesn't hold.
  124. for (BasicBlock *P : predecessors(DestBB)) {
  125. if (P == TIBB)
  126. continue; // The new block is known.
  127. if (LI->getLoopFor(P) != TIL) {
  128. // No need to re-simplify, it wasn't to start with.
  129. LoopPreds.clear();
  130. break;
  131. }
  132. LoopPreds.push_back(P);
  133. }
  134. // Loop-simplify form can be preserved, if we can split all in-loop
  135. // predecessors.
  136. if (any_of(LoopPreds, [](BasicBlock *Pred) {
  137. return isa<IndirectBrInst>(Pred->getTerminator());
  138. })) {
  139. if (Options.PreserveLoopSimplify)
  140. return nullptr;
  141. LoopPreds.clear();
  142. }
  143. }
  144. }
  145. // Create a new basic block, linking it into the CFG.
  146. BasicBlock *NewBB = nullptr;
  147. if (BBName.str() != "")
  148. NewBB = BasicBlock::Create(TI->getContext(), BBName);
  149. else
  150. NewBB = BasicBlock::Create(TI->getContext(), TIBB->getName() + "." +
  151. DestBB->getName() +
  152. "_crit_edge");
  153. // Create our unconditional branch.
  154. BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
  155. NewBI->setDebugLoc(TI->getDebugLoc());
  156. // Insert the block into the function... right after the block TI lives in.
  157. Function &F = *TIBB->getParent();
  158. Function::iterator FBBI = TIBB->getIterator();
  159. F.insert(++FBBI, NewBB);
  160. // Branch to the new block, breaking the edge.
  161. TI->setSuccessor(SuccNum, NewBB);
  162. // If there are any PHI nodes in DestBB, we need to update them so that they
  163. // merge incoming values from NewBB instead of from TIBB.
  164. {
  165. unsigned BBIdx = 0;
  166. for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
  167. // We no longer enter through TIBB, now we come in through NewBB.
  168. // Revector exactly one entry in the PHI node that used to come from
  169. // TIBB to come from NewBB.
  170. PHINode *PN = cast<PHINode>(I);
  171. // Reuse the previous value of BBIdx if it lines up. In cases where we
  172. // have multiple phi nodes with *lots* of predecessors, this is a speed
  173. // win because we don't have to scan the PHI looking for TIBB. This
  174. // happens because the BB list of PHI nodes are usually in the same
  175. // order.
  176. if (PN->getIncomingBlock(BBIdx) != TIBB)
  177. BBIdx = PN->getBasicBlockIndex(TIBB);
  178. PN->setIncomingBlock(BBIdx, NewBB);
  179. }
  180. }
  181. // If there are any other edges from TIBB to DestBB, update those to go
  182. // through the split block, making those edges non-critical as well (and
  183. // reducing the number of phi entries in the DestBB if relevant).
  184. if (Options.MergeIdenticalEdges) {
  185. for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
  186. if (TI->getSuccessor(i) != DestBB) continue;
  187. // Remove an entry for TIBB from DestBB phi nodes.
  188. DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
  189. // We found another edge to DestBB, go to NewBB instead.
  190. TI->setSuccessor(i, NewBB);
  191. }
  192. }
  193. // If we have nothing to update, just return.
  194. auto *DT = Options.DT;
  195. auto *PDT = Options.PDT;
  196. auto *MSSAU = Options.MSSAU;
  197. if (MSSAU)
  198. MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
  199. DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
  200. if (!DT && !PDT && !LI)
  201. return NewBB;
  202. if (DT || PDT) {
  203. // Update the DominatorTree.
  204. // ---> NewBB -----\
  205. // / V
  206. // TIBB -------\\------> DestBB
  207. //
  208. // First, inform the DT about the new path from TIBB to DestBB via NewBB,
  209. // then delete the old edge from TIBB to DestBB. By doing this in that order
  210. // DestBB stays reachable in the DT the whole time and its subtree doesn't
  211. // get disconnected.
  212. SmallVector<DominatorTree::UpdateType, 3> Updates;
  213. Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
  214. Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
  215. if (!llvm::is_contained(successors(TIBB), DestBB))
  216. Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
  217. if (DT)
  218. DT->applyUpdates(Updates);
  219. if (PDT)
  220. PDT->applyUpdates(Updates);
  221. }
  222. // Update LoopInfo if it is around.
  223. if (LI) {
  224. if (Loop *TIL = LI->getLoopFor(TIBB)) {
  225. // If one or the other blocks were not in a loop, the new block is not
  226. // either, and thus LI doesn't need to be updated.
  227. if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
  228. if (TIL == DestLoop) {
  229. // Both in the same loop, the NewBB joins loop.
  230. DestLoop->addBasicBlockToLoop(NewBB, *LI);
  231. } else if (TIL->contains(DestLoop)) {
  232. // Edge from an outer loop to an inner loop. Add to the outer loop.
  233. TIL->addBasicBlockToLoop(NewBB, *LI);
  234. } else if (DestLoop->contains(TIL)) {
  235. // Edge from an inner loop to an outer loop. Add to the outer loop.
  236. DestLoop->addBasicBlockToLoop(NewBB, *LI);
  237. } else {
  238. // Edge from two loops with no containment relation. Because these
  239. // are natural loops, we know that the destination block must be the
  240. // header of its loop (adding a branch into a loop elsewhere would
  241. // create an irreducible loop).
  242. assert(DestLoop->getHeader() == DestBB &&
  243. "Should not create irreducible loops!");
  244. if (Loop *P = DestLoop->getParentLoop())
  245. P->addBasicBlockToLoop(NewBB, *LI);
  246. }
  247. }
  248. // If TIBB is in a loop and DestBB is outside of that loop, we may need
  249. // to update LoopSimplify form and LCSSA form.
  250. if (!TIL->contains(DestBB)) {
  251. assert(!TIL->contains(NewBB) &&
  252. "Split point for loop exit is contained in loop!");
  253. // Update LCSSA form in the newly created exit block.
  254. if (Options.PreserveLCSSA) {
  255. createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
  256. }
  257. if (!LoopPreds.empty()) {
  258. assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
  259. BasicBlock *NewExitBB = SplitBlockPredecessors(
  260. DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
  261. if (Options.PreserveLCSSA)
  262. createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
  263. }
  264. }
  265. }
  266. }
  267. return NewBB;
  268. }
  269. // Return the unique indirectbr predecessor of a block. This may return null
  270. // even if such a predecessor exists, if it's not useful for splitting.
  271. // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
  272. // predecessors of BB.
  273. static BasicBlock *
  274. findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
  275. // Verify we have exactly one IBR predecessor.
  276. // Conservatively bail out if one of the other predecessors is not a "regular"
  277. // terminator (that is, not a switch or a br).
  278. BasicBlock *IBB = nullptr;
  279. for (BasicBlock *PredBB : predecessors(BB)) {
  280. Instruction *PredTerm = PredBB->getTerminator();
  281. switch (PredTerm->getOpcode()) {
  282. case Instruction::IndirectBr:
  283. if (IBB)
  284. return nullptr;
  285. IBB = PredBB;
  286. break;
  287. case Instruction::Br:
  288. case Instruction::Switch:
  289. OtherPreds.push_back(PredBB);
  290. continue;
  291. default:
  292. return nullptr;
  293. }
  294. }
  295. return IBB;
  296. }
  297. bool llvm::SplitIndirectBrCriticalEdges(Function &F,
  298. bool IgnoreBlocksWithoutPHI,
  299. BranchProbabilityInfo *BPI,
  300. BlockFrequencyInfo *BFI) {
  301. // Check whether the function has any indirectbrs, and collect which blocks
  302. // they may jump to. Since most functions don't have indirect branches,
  303. // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
  304. SmallSetVector<BasicBlock *, 16> Targets;
  305. for (auto &BB : F) {
  306. auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
  307. if (!IBI)
  308. continue;
  309. for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
  310. Targets.insert(IBI->getSuccessor(Succ));
  311. }
  312. if (Targets.empty())
  313. return false;
  314. bool ShouldUpdateAnalysis = BPI && BFI;
  315. bool Changed = false;
  316. for (BasicBlock *Target : Targets) {
  317. if (IgnoreBlocksWithoutPHI && Target->phis().empty())
  318. continue;
  319. SmallVector<BasicBlock *, 16> OtherPreds;
  320. BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
  321. // If we did not found an indirectbr, or the indirectbr is the only
  322. // incoming edge, this isn't the kind of edge we're looking for.
  323. if (!IBRPred || OtherPreds.empty())
  324. continue;
  325. // Don't even think about ehpads/landingpads.
  326. Instruction *FirstNonPHI = Target->getFirstNonPHI();
  327. if (FirstNonPHI->isEHPad() || Target->isLandingPad())
  328. continue;
  329. // Remember edge probabilities if needed.
  330. SmallVector<BranchProbability, 4> EdgeProbabilities;
  331. if (ShouldUpdateAnalysis) {
  332. EdgeProbabilities.reserve(Target->getTerminator()->getNumSuccessors());
  333. for (unsigned I = 0, E = Target->getTerminator()->getNumSuccessors();
  334. I < E; ++I)
  335. EdgeProbabilities.emplace_back(BPI->getEdgeProbability(Target, I));
  336. BPI->eraseBlock(Target);
  337. }
  338. BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
  339. if (ShouldUpdateAnalysis) {
  340. // Copy the BFI/BPI from Target to BodyBlock.
  341. BPI->setEdgeProbability(BodyBlock, EdgeProbabilities);
  342. BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
  343. }
  344. // It's possible Target was its own successor through an indirectbr.
  345. // In this case, the indirectbr now comes from BodyBlock.
  346. if (IBRPred == Target)
  347. IBRPred = BodyBlock;
  348. // At this point Target only has PHIs, and BodyBlock has the rest of the
  349. // block's body. Create a copy of Target that will be used by the "direct"
  350. // preds.
  351. ValueToValueMapTy VMap;
  352. BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
  353. BlockFrequency BlockFreqForDirectSucc;
  354. for (BasicBlock *Pred : OtherPreds) {
  355. // If the target is a loop to itself, then the terminator of the split
  356. // block (BodyBlock) needs to be updated.
  357. BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
  358. Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
  359. if (ShouldUpdateAnalysis)
  360. BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
  361. BPI->getEdgeProbability(Src, DirectSucc);
  362. }
  363. if (ShouldUpdateAnalysis) {
  364. BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
  365. BlockFrequency NewBlockFreqForTarget =
  366. BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
  367. BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
  368. }
  369. // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
  370. // they are clones, so the number of PHIs are the same.
  371. // (a) Remove the edge coming from IBRPred from the "Direct" PHI
  372. // (b) Leave that as the only edge in the "Indirect" PHI.
  373. // (c) Merge the two in the body block.
  374. BasicBlock::iterator Indirect = Target->begin(),
  375. End = Target->getFirstNonPHI()->getIterator();
  376. BasicBlock::iterator Direct = DirectSucc->begin();
  377. BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
  378. assert(&*End == Target->getTerminator() &&
  379. "Block was expected to only contain PHIs");
  380. while (Indirect != End) {
  381. PHINode *DirPHI = cast<PHINode>(Direct);
  382. PHINode *IndPHI = cast<PHINode>(Indirect);
  383. // Now, clean up - the direct block shouldn't get the indirect value,
  384. // and vice versa.
  385. DirPHI->removeIncomingValue(IBRPred);
  386. Direct++;
  387. // Advance the pointer here, to avoid invalidation issues when the old
  388. // PHI is erased.
  389. Indirect++;
  390. PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
  391. NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
  392. IBRPred);
  393. // Create a PHI in the body block, to merge the direct and indirect
  394. // predecessors.
  395. PHINode *MergePHI =
  396. PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
  397. MergePHI->addIncoming(NewIndPHI, Target);
  398. MergePHI->addIncoming(DirPHI, DirectSucc);
  399. IndPHI->replaceAllUsesWith(MergePHI);
  400. IndPHI->eraseFromParent();
  401. }
  402. Changed = true;
  403. }
  404. return Changed;
  405. }