1 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
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 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
10 // top-level loop into its own new function. If the loop is the ONLY loop in a
11 // given function, it is not touched. This is a pass most useful for debugging
12 // via bugpoint.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Transforms/IPO.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Utils.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/CodeExtractor.h"
30 #include <fstream>
31 #include <set>
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "loop-extract"
35 
36 STATISTIC(NumExtracted, "Number of loops extracted");
37 
38 namespace {
39   struct LoopExtractor : public LoopPass {
40     static char ID; // Pass identification, replacement for typeid
41     unsigned NumLoops;
42 
43     explicit LoopExtractor(unsigned numLoops = ~0)
44       : LoopPass(ID), NumLoops(numLoops) {
45         initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
46       }
47 
48     bool runOnLoop(Loop *L, LPPassManager &) override;
49 
50     void getAnalysisUsage(AnalysisUsage &AU) const override {
51       AU.addRequiredID(BreakCriticalEdgesID);
52       AU.addRequiredID(LoopSimplifyID);
53       AU.addRequired<DominatorTreeWrapperPass>();
54       AU.addRequired<LoopInfoWrapperPass>();
55       AU.addUsedIfAvailable<AssumptionCacheTracker>();
56     }
57   };
58 }
59 
60 char LoopExtractor::ID = 0;
61 INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
62                       "Extract loops into new functions", false, false)
63 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
64 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
65 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
66 INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
67                     "Extract loops into new functions", false, false)
68 
69 namespace {
70   /// SingleLoopExtractor - For bugpoint.
71   struct SingleLoopExtractor : public LoopExtractor {
72     static char ID; // Pass identification, replacement for typeid
73     SingleLoopExtractor() : LoopExtractor(1) {}
74   };
75 } // End anonymous namespace
76 
77 char SingleLoopExtractor::ID = 0;
78 INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
79                 "Extract at most one loop into a new function", false, false)
80 
81 // createLoopExtractorPass - This pass extracts all natural loops from the
82 // program into a function if it can.
83 //
84 Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
85 
86 bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
87   if (skipLoop(L))
88     return false;
89 
90   // Only visit top-level loops.
91   if (L->getParentLoop())
92     return false;
93 
94   // If LoopSimplify form is not available, stay out of trouble.
95   if (!L->isLoopSimplifyForm())
96     return false;
97 
98   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
99   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
100   bool Changed = false;
101 
102   // If there is more than one top-level loop in this function, extract all of
103   // the loops. Otherwise there is exactly one top-level loop; in this case if
104   // this function is more than a minimal wrapper around the loop, extract
105   // the loop.
106   bool ShouldExtractLoop = false;
107 
108   // Extract the loop if the entry block doesn't branch to the loop header.
109   Instruction *EntryTI =
110       L->getHeader()->getParent()->getEntryBlock().getTerminator();
111   if (!isa<BranchInst>(EntryTI) ||
112       !cast<BranchInst>(EntryTI)->isUnconditional() ||
113       EntryTI->getSuccessor(0) != L->getHeader()) {
114     ShouldExtractLoop = true;
115   } else {
116     // Check to see if any exits from the loop are more than just return
117     // blocks.
118     SmallVector<BasicBlock*, 8> ExitBlocks;
119     L->getExitBlocks(ExitBlocks);
120     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
121       if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
122         ShouldExtractLoop = true;
123         break;
124       }
125   }
126 
127   if (ShouldExtractLoop) {
128     // We must omit EH pads. EH pads must accompany the invoke
129     // instruction. But this would result in a loop in the extracted
130     // function. An infinite cycle occurs when it tries to extract that loop as
131     // well.
132     SmallVector<BasicBlock*, 8> ExitBlocks;
133     L->getExitBlocks(ExitBlocks);
134     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
135       if (ExitBlocks[i]->isEHPad()) {
136         ShouldExtractLoop = false;
137         break;
138       }
139   }
140 
141   if (ShouldExtractLoop) {
142     if (NumLoops == 0) return Changed;
143     --NumLoops;
144     AssumptionCache *AC = nullptr;
145     Function &Func = *L->getHeader()->getParent();
146     if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
147       AC = ACT->lookupAssumptionCache(Func);
148     CodeExtractorAnalysisCache CEAC(Func);
149     CodeExtractor Extractor(DT, *L, false, nullptr, nullptr, AC);
150     if (Extractor.extractCodeRegion(CEAC) != nullptr) {
151       Changed = true;
152       // After extraction, the loop is replaced by a function call, so
153       // we shouldn't try to run any more loop passes on it.
154       LPM.markLoopAsDeleted(*L);
155       LI.erase(L);
156     }
157     ++NumExtracted;
158   }
159 
160   return Changed;
161 }
162 
163 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
164 // program into a function if it can.  This is used by bugpoint.
165 //
166 Pass *llvm::createSingleLoopExtractorPass() {
167   return new SingleLoopExtractor();
168 }
169