FixIrreducible.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //===- FixIrreducible.cpp - Convert irreducible control-flow into loops ---===//
  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. // An irreducible SCC is one which has multiple "header" blocks, i.e., blocks
  10. // with control-flow edges incident from outside the SCC. This pass converts a
  11. // irreducible SCC into a natural loop by applying the following transformation:
  12. //
  13. // 1. Collect the set of headers H of the SCC.
  14. // 2. Collect the set of predecessors P of these headers. These may be inside as
  15. // well as outside the SCC.
  16. // 3. Create block N and redirect every edge from set P to set H through N.
  17. //
  18. // This converts the SCC into a natural loop with N as the header: N is the only
  19. // block with edges incident from outside the SCC, and all backedges in the SCC
  20. // are incident on N, i.e., for every backedge, the head now dominates the tail.
  21. //
  22. // INPUT CFG: The blocks A and B form an irreducible loop with two headers.
  23. //
  24. // Entry
  25. // / \
  26. // v v
  27. // A ----> B
  28. // ^ /|
  29. // `----' |
  30. // v
  31. // Exit
  32. //
  33. // OUTPUT CFG: Edges incident on A and B are now redirected through a
  34. // new block N, forming a natural loop consisting of N, A and B.
  35. //
  36. // Entry
  37. // |
  38. // v
  39. // .---> N <---.
  40. // / / \ \
  41. // | / \ |
  42. // \ v v /
  43. // `-- A B --'
  44. // |
  45. // v
  46. // Exit
  47. //
  48. // The transformation is applied to every maximal SCC that is not already
  49. // recognized as a loop. The pass operates on all maximal SCCs found in the
  50. // function body outside of any loop, as well as those found inside each loop,
  51. // including inside any newly created loops. This ensures that any SCC hidden
  52. // inside a maximal SCC is also transformed.
  53. //
  54. // The actual transformation is handled by function CreateControlFlowHub, which
  55. // takes a set of incoming blocks (the predecessors) and outgoing blocks (the
  56. // headers). The function also moves every PHINode in an outgoing block to the
  57. // hub. Since the hub dominates all the outgoing blocks, each such PHINode
  58. // continues to dominate its uses. Since every header in an SCC has at least two
  59. // predecessors, every value used in the header (or later) but defined in a
  60. // predecessor (or earlier) is represented by a PHINode in a header. Hence the
  61. // above handling of PHINodes is sufficient and no further processing is
  62. // required to restore SSA.
  63. //
  64. // Limitation: The pass cannot handle switch statements and indirect
  65. // branches. Both must be lowered to plain branches first.
  66. //
  67. //===----------------------------------------------------------------------===//
  68. #include "llvm/Transforms/Utils/FixIrreducible.h"
  69. #include "llvm/ADT/SCCIterator.h"
  70. #include "llvm/Analysis/LoopIterator.h"
  71. #include "llvm/InitializePasses.h"
  72. #include "llvm/Pass.h"
  73. #include "llvm/Transforms/Utils.h"
  74. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  75. #define DEBUG_TYPE "fix-irreducible"
  76. using namespace llvm;
  77. namespace {
  78. struct FixIrreducible : public FunctionPass {
  79. static char ID;
  80. FixIrreducible() : FunctionPass(ID) {
  81. initializeFixIrreduciblePass(*PassRegistry::getPassRegistry());
  82. }
  83. void getAnalysisUsage(AnalysisUsage &AU) const override {
  84. AU.addRequiredID(LowerSwitchID);
  85. AU.addRequired<DominatorTreeWrapperPass>();
  86. AU.addRequired<LoopInfoWrapperPass>();
  87. AU.addPreservedID(LowerSwitchID);
  88. AU.addPreserved<DominatorTreeWrapperPass>();
  89. AU.addPreserved<LoopInfoWrapperPass>();
  90. }
  91. bool runOnFunction(Function &F) override;
  92. };
  93. } // namespace
  94. char FixIrreducible::ID = 0;
  95. FunctionPass *llvm::createFixIrreduciblePass() { return new FixIrreducible(); }
  96. INITIALIZE_PASS_BEGIN(FixIrreducible, "fix-irreducible",
  97. "Convert irreducible control-flow into natural loops",
  98. false /* Only looks at CFG */, false /* Analysis Pass */)
  99. INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass)
  100. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  101. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  102. INITIALIZE_PASS_END(FixIrreducible, "fix-irreducible",
  103. "Convert irreducible control-flow into natural loops",
  104. false /* Only looks at CFG */, false /* Analysis Pass */)
  105. // When a new loop is created, existing children of the parent loop may now be
  106. // fully inside the new loop. Reconnect these as children of the new loop.
  107. static void reconnectChildLoops(LoopInfo &LI, Loop *ParentLoop, Loop *NewLoop,
  108. SetVector<BasicBlock *> &Blocks,
  109. SetVector<BasicBlock *> &Headers) {
  110. auto &CandidateLoops = ParentLoop ? ParentLoop->getSubLoopsVector()
  111. : LI.getTopLevelLoopsVector();
  112. // The new loop cannot be its own child, and any candidate is a
  113. // child iff its header is owned by the new loop. Move all the
  114. // children to a new vector.
  115. auto FirstChild = std::partition(
  116. CandidateLoops.begin(), CandidateLoops.end(), [&](Loop *L) {
  117. return L == NewLoop || Blocks.count(L->getHeader()) == 0;
  118. });
  119. SmallVector<Loop *, 8> ChildLoops(FirstChild, CandidateLoops.end());
  120. CandidateLoops.erase(FirstChild, CandidateLoops.end());
  121. for (auto II = ChildLoops.begin(), IE = ChildLoops.end(); II != IE; ++II) {
  122. auto Child = *II;
  123. LLVM_DEBUG(dbgs() << "child loop: " << Child->getHeader()->getName()
  124. << "\n");
  125. // TODO: A child loop whose header is also a header in the current
  126. // SCC gets destroyed since its backedges are removed. That may
  127. // not be necessary if we can retain such backedges.
  128. if (Headers.count(Child->getHeader())) {
  129. for (auto BB : Child->blocks()) {
  130. LI.changeLoopFor(BB, NewLoop);
  131. LLVM_DEBUG(dbgs() << "moved block from child: " << BB->getName()
  132. << "\n");
  133. }
  134. LI.destroy(Child);
  135. LLVM_DEBUG(dbgs() << "subsumed child loop (common header)\n");
  136. continue;
  137. }
  138. Child->setParentLoop(nullptr);
  139. NewLoop->addChildLoop(Child);
  140. LLVM_DEBUG(dbgs() << "added child loop to new loop\n");
  141. }
  142. }
  143. // Given a set of blocks and headers in an irreducible SCC, convert it into a
  144. // natural loop. Also insert this new loop at its appropriate place in the
  145. // hierarchy of loops.
  146. static void createNaturalLoopInternal(LoopInfo &LI, DominatorTree &DT,
  147. Loop *ParentLoop,
  148. SetVector<BasicBlock *> &Blocks,
  149. SetVector<BasicBlock *> &Headers) {
  150. #ifndef NDEBUG
  151. // All headers are part of the SCC
  152. for (auto H : Headers) {
  153. assert(Blocks.count(H));
  154. }
  155. #endif
  156. SetVector<BasicBlock *> Predecessors;
  157. for (auto H : Headers) {
  158. for (auto P : predecessors(H)) {
  159. Predecessors.insert(P);
  160. }
  161. }
  162. LLVM_DEBUG(
  163. dbgs() << "Found predecessors:";
  164. for (auto P : Predecessors) {
  165. dbgs() << " " << P->getName();
  166. }
  167. dbgs() << "\n");
  168. // Redirect all the backedges through a "hub" consisting of a series
  169. // of guard blocks that manage the flow of control from the
  170. // predecessors to the headers.
  171. SmallVector<BasicBlock *, 8> GuardBlocks;
  172. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  173. CreateControlFlowHub(&DTU, GuardBlocks, Predecessors, Headers, "irr");
  174. #if defined(EXPENSIVE_CHECKS)
  175. assert(DT.verify(DominatorTree::VerificationLevel::Full));
  176. #else
  177. assert(DT.verify(DominatorTree::VerificationLevel::Fast));
  178. #endif
  179. // Create a new loop from the now-transformed cycle
  180. auto NewLoop = LI.AllocateLoop();
  181. if (ParentLoop) {
  182. ParentLoop->addChildLoop(NewLoop);
  183. } else {
  184. LI.addTopLevelLoop(NewLoop);
  185. }
  186. // Add the guard blocks to the new loop. The first guard block is
  187. // the head of all the backedges, and it is the first to be inserted
  188. // in the loop. This ensures that it is recognized as the
  189. // header. Since the new loop is already in LoopInfo, the new blocks
  190. // are also propagated up the chain of parent loops.
  191. for (auto G : GuardBlocks) {
  192. LLVM_DEBUG(dbgs() << "added guard block: " << G->getName() << "\n");
  193. NewLoop->addBasicBlockToLoop(G, LI);
  194. }
  195. // Add the SCC blocks to the new loop.
  196. for (auto BB : Blocks) {
  197. NewLoop->addBlockEntry(BB);
  198. if (LI.getLoopFor(BB) == ParentLoop) {
  199. LLVM_DEBUG(dbgs() << "moved block from parent: " << BB->getName()
  200. << "\n");
  201. LI.changeLoopFor(BB, NewLoop);
  202. } else {
  203. LLVM_DEBUG(dbgs() << "added block from child: " << BB->getName() << "\n");
  204. }
  205. }
  206. LLVM_DEBUG(dbgs() << "header for new loop: "
  207. << NewLoop->getHeader()->getName() << "\n");
  208. reconnectChildLoops(LI, ParentLoop, NewLoop, Blocks, Headers);
  209. NewLoop->verifyLoop();
  210. if (ParentLoop) {
  211. ParentLoop->verifyLoop();
  212. }
  213. #if defined(EXPENSIVE_CHECKS)
  214. LI.verify(DT);
  215. #endif // EXPENSIVE_CHECKS
  216. }
  217. namespace llvm {
  218. // Enable the graph traits required for traversing a Loop body.
  219. template <> struct GraphTraits<Loop> : LoopBodyTraits {};
  220. } // namespace llvm
  221. // Overloaded wrappers to go with the function template below.
  222. static BasicBlock *unwrapBlock(BasicBlock *B) { return B; }
  223. static BasicBlock *unwrapBlock(LoopBodyTraits::NodeRef &N) { return N.second; }
  224. static void createNaturalLoop(LoopInfo &LI, DominatorTree &DT, Function *F,
  225. SetVector<BasicBlock *> &Blocks,
  226. SetVector<BasicBlock *> &Headers) {
  227. createNaturalLoopInternal(LI, DT, nullptr, Blocks, Headers);
  228. }
  229. static void createNaturalLoop(LoopInfo &LI, DominatorTree &DT, Loop &L,
  230. SetVector<BasicBlock *> &Blocks,
  231. SetVector<BasicBlock *> &Headers) {
  232. createNaturalLoopInternal(LI, DT, &L, Blocks, Headers);
  233. }
  234. // Convert irreducible SCCs; Graph G may be a Function* or a Loop&.
  235. template <class Graph>
  236. static bool makeReducible(LoopInfo &LI, DominatorTree &DT, Graph &&G) {
  237. bool Changed = false;
  238. for (auto Scc = scc_begin(G); !Scc.isAtEnd(); ++Scc) {
  239. if (Scc->size() < 2)
  240. continue;
  241. SetVector<BasicBlock *> Blocks;
  242. LLVM_DEBUG(dbgs() << "Found SCC:");
  243. for (auto N : *Scc) {
  244. auto BB = unwrapBlock(N);
  245. LLVM_DEBUG(dbgs() << " " << BB->getName());
  246. Blocks.insert(BB);
  247. }
  248. LLVM_DEBUG(dbgs() << "\n");
  249. // Minor optimization: The SCC blocks are usually discovered in an order
  250. // that is the opposite of the order in which these blocks appear as branch
  251. // targets. This results in a lot of condition inversions in the control
  252. // flow out of the new ControlFlowHub, which can be mitigated if the orders
  253. // match. So we discover the headers using the reverse of the block order.
  254. SetVector<BasicBlock *> Headers;
  255. LLVM_DEBUG(dbgs() << "Found headers:");
  256. for (auto BB : reverse(Blocks)) {
  257. for (const auto P : predecessors(BB)) {
  258. // Skip unreachable predecessors.
  259. if (!DT.isReachableFromEntry(P))
  260. continue;
  261. if (!Blocks.count(P)) {
  262. LLVM_DEBUG(dbgs() << " " << BB->getName());
  263. Headers.insert(BB);
  264. break;
  265. }
  266. }
  267. }
  268. LLVM_DEBUG(dbgs() << "\n");
  269. if (Headers.size() == 1) {
  270. assert(LI.isLoopHeader(Headers.front()));
  271. LLVM_DEBUG(dbgs() << "Natural loop with a single header: skipped\n");
  272. continue;
  273. }
  274. createNaturalLoop(LI, DT, G, Blocks, Headers);
  275. Changed = true;
  276. }
  277. return Changed;
  278. }
  279. static bool FixIrreducibleImpl(Function &F, LoopInfo &LI, DominatorTree &DT) {
  280. LLVM_DEBUG(dbgs() << "===== Fix irreducible control-flow in function: "
  281. << F.getName() << "\n");
  282. bool Changed = false;
  283. SmallVector<Loop *, 8> WorkList;
  284. LLVM_DEBUG(dbgs() << "visiting top-level\n");
  285. Changed |= makeReducible(LI, DT, &F);
  286. // Any SCCs reduced are now already in the list of top-level loops, so simply
  287. // add them all to the worklist.
  288. append_range(WorkList, LI);
  289. while (!WorkList.empty()) {
  290. auto L = WorkList.pop_back_val();
  291. LLVM_DEBUG(dbgs() << "visiting loop with header "
  292. << L->getHeader()->getName() << "\n");
  293. Changed |= makeReducible(LI, DT, *L);
  294. // Any SCCs reduced are now already in the list of child loops, so simply
  295. // add them all to the worklist.
  296. WorkList.append(L->begin(), L->end());
  297. }
  298. return Changed;
  299. }
  300. bool FixIrreducible::runOnFunction(Function &F) {
  301. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  302. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  303. return FixIrreducibleImpl(F, LI, DT);
  304. }
  305. PreservedAnalyses FixIrreduciblePass::run(Function &F,
  306. FunctionAnalysisManager &AM) {
  307. auto &LI = AM.getResult<LoopAnalysis>(F);
  308. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  309. if (!FixIrreducibleImpl(F, LI, DT))
  310. return PreservedAnalyses::all();
  311. PreservedAnalyses PA;
  312. PA.preserve<LoopAnalysis>();
  313. PA.preserve<DominatorTreeAnalysis>();
  314. return PA;
  315. }