Omit extracting a loop if one of the exits is a landing pad.
[oota-llvm.git] / lib / Transforms / IPO / LoopExtractor.cpp
1 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
11 // top-level loop into its own new function. If the loop is the ONLY loop in a
12 // given function, it is not touched. This is a pass most useful for debugging
13 // via bugpoint.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "loop-extract"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/FunctionUtils.h"
28 #include "llvm/ADT/Statistic.h"
29 #include <fstream>
30 #include <set>
31 using namespace llvm;
32
33 STATISTIC(NumExtracted, "Number of loops extracted");
34
35 namespace {
36   struct LoopExtractor : public LoopPass {
37     static char ID; // Pass identification, replacement for typeid
38     unsigned NumLoops;
39
40     explicit LoopExtractor(unsigned numLoops = ~0) 
41       : LoopPass(ID), NumLoops(numLoops) {
42         initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
43       }
44
45     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
46
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       AU.addRequiredID(BreakCriticalEdgesID);
49       AU.addRequiredID(LoopSimplifyID);
50       AU.addRequired<DominatorTree>();
51     }
52   };
53 }
54
55 char LoopExtractor::ID = 0;
56 INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
57                       "Extract loops into new functions", false, false)
58 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
59 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
60 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
61 INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
62                     "Extract loops into new functions", false, false)
63
64 namespace {
65   /// SingleLoopExtractor - For bugpoint.
66   struct SingleLoopExtractor : public LoopExtractor {
67     static char ID; // Pass identification, replacement for typeid
68     SingleLoopExtractor() : LoopExtractor(1) {}
69   };
70 } // End anonymous namespace
71
72 char SingleLoopExtractor::ID = 0;
73 INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
74                 "Extract at most one loop into a new function", false, false)
75
76 // createLoopExtractorPass - This pass extracts all natural loops from the
77 // program into a function if it can.
78 //
79 Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
80
81 bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
82   // Only visit top-level loops.
83   if (L->getParentLoop())
84     return false;
85
86   // If LoopSimplify form is not available, stay out of trouble.
87   if (!L->isLoopSimplifyForm())
88     return false;
89
90   DominatorTree &DT = getAnalysis<DominatorTree>();
91   bool Changed = false;
92
93   // If there is more than one top-level loop in this function, extract all of
94   // the loops. Otherwise there is exactly one top-level loop; in this case if
95   // this function is more than a minimal wrapper around the loop, extract
96   // the loop.
97   bool ShouldExtractLoop = false;
98
99   // Extract the loop if the entry block doesn't branch to the loop header.
100   TerminatorInst *EntryTI =
101     L->getHeader()->getParent()->getEntryBlock().getTerminator();
102   if (!isa<BranchInst>(EntryTI) ||
103       !cast<BranchInst>(EntryTI)->isUnconditional() ||
104       EntryTI->getSuccessor(0) != L->getHeader()) {
105     ShouldExtractLoop = true;
106   } else {
107     // Check to see if any exits from the loop are more than just return
108     // blocks. We also must omit landing pads. Landing pads must accompany the
109     // invoke instruction. But this would result in a loop in the extracted
110     // function. An infinite cycle occurs when it tries to extract that loop as
111     // well.
112     SmallVector<BasicBlock*, 8> ExitBlocks;
113     L->getExitBlocks(ExitBlocks);
114     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
115       if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator()))
116         ShouldExtractLoop = true;
117       if (ExitBlocks[i]->isLandingPad()) {
118         ShouldExtractLoop = false;
119         break;
120       }
121     }
122   }
123   if (ShouldExtractLoop) {
124     if (NumLoops == 0) return Changed;
125     --NumLoops;
126     if (ExtractLoop(DT, L) != 0) {
127       Changed = true;
128       // After extraction, the loop is replaced by a function call, so
129       // we shouldn't try to run any more loop passes on it.
130       LPM.deleteLoopFromQueue(L);
131     }
132     ++NumExtracted;
133   }
134
135   return Changed;
136 }
137
138 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
139 // program into a function if it can.  This is used by bugpoint.
140 //
141 Pass *llvm::createSingleLoopExtractorPass() {
142   return new SingleLoopExtractor();
143 }
144
145
146 // BlockFile - A file which contains a list of blocks that should not be
147 // extracted.
148 static cl::opt<std::string>
149 BlockFile("extract-blocks-file", cl::value_desc("filename"),
150           cl::desc("A file containing list of basic blocks to not extract"),
151           cl::Hidden);
152
153 namespace {
154   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
155   /// from the module into their own functions except for those specified by the
156   /// BlocksToNotExtract list.
157   class BlockExtractorPass : public ModulePass {
158     void LoadFile(const char *Filename);
159     void SplitLandingPadPreds(Function *F);
160
161     std::vector<BasicBlock*> BlocksToNotExtract;
162     std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
163   public:
164     static char ID; // Pass identification, replacement for typeid
165     BlockExtractorPass() : ModulePass(ID) {
166       if (!BlockFile.empty())
167         LoadFile(BlockFile.c_str());
168     }
169
170     bool runOnModule(Module &M);
171   };
172 }
173
174 char BlockExtractorPass::ID = 0;
175 INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
176                 "Extract Basic Blocks From Module (for bugpoint use)",
177                 false, false)
178
179 // createBlockExtractorPass - This pass extracts all blocks (except those
180 // specified in the argument list) from the functions in the module.
181 //
182 ModulePass *llvm::createBlockExtractorPass() {
183   return new BlockExtractorPass();
184 }
185
186 void BlockExtractorPass::LoadFile(const char *Filename) {
187   // Load the BlockFile...
188   std::ifstream In(Filename);
189   if (!In.good()) {
190     errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
191            << "'!\n";
192     return;
193   }
194   while (In) {
195     std::string FunctionName, BlockName;
196     In >> FunctionName;
197     In >> BlockName;
198     if (!BlockName.empty())
199       BlocksToNotExtractByName.push_back(
200           std::make_pair(FunctionName, BlockName));
201   }
202 }
203
204 /// SplitLandingPadPreds - The landing pad needs to be extracted with the invoke
205 /// instruction. The critical edge breaker will refuse to break critical edges
206 /// to a landing pad. So do them here. After this method runs, all landing pads
207 /// should have only one predecessor.
208 void BlockExtractorPass::SplitLandingPadPreds(Function *F) {
209   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
210     InvokeInst *II = dyn_cast<InvokeInst>(I);
211     if (!II) continue;
212     BasicBlock *Parent = II->getParent();
213     BasicBlock *LPad = II->getUnwindDest();
214
215     // Look through the landing pad's predecessors. If one of them ends in an
216     // 'invoke', then we want to split the landing pad.
217     bool Split = false;
218     for (pred_iterator
219            PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ++PI) {
220       BasicBlock *BB = *PI;
221       if (BB->isLandingPad() && BB != Parent &&
222           isa<InvokeInst>(Parent->getTerminator())) {
223         Split = true;
224         break;
225       }
226     }
227
228     if (!Split) continue;
229
230     SmallVector<BasicBlock*, 2> NewBBs;
231     SplitLandingPadPredecessors(LPad, Parent, ".1", ".2", 0, NewBBs);
232   }
233 }
234
235 bool BlockExtractorPass::runOnModule(Module &M) {
236   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
237   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
238     BasicBlock *BB = BlocksToNotExtract[i];
239     Function *F = BB->getParent();
240
241     // Map the corresponding function in this module.
242     Function *MF = M.getFunction(F->getName());
243     assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
244
245     // Figure out which index the basic block is in its function.
246     Function::iterator BBI = MF->begin();
247     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
248     TranslatedBlocksToNotExtract.insert(BBI);
249   }
250
251   while (!BlocksToNotExtractByName.empty()) {
252     // There's no way to find BBs by name without looking at every BB inside
253     // every Function. Fortunately, this is always empty except when used by
254     // bugpoint in which case correctness is more important than performance.
255
256     std::string &FuncName  = BlocksToNotExtractByName.back().first;
257     std::string &BlockName = BlocksToNotExtractByName.back().second;
258
259     for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
260       Function &F = *FI;
261       if (F.getName() != FuncName) continue;
262
263       for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
264         BasicBlock &BB = *BI;
265         if (BB.getName() != BlockName) continue;
266
267         TranslatedBlocksToNotExtract.insert(BI);
268       }
269     }
270
271     BlocksToNotExtractByName.pop_back();
272   }
273
274   // Now that we know which blocks to not extract, figure out which ones we WANT
275   // to extract.
276   std::vector<BasicBlock*> BlocksToExtract;
277   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
278     SplitLandingPadPreds(&*F);
279     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
280       if (!TranslatedBlocksToNotExtract.count(BB))
281         BlocksToExtract.push_back(BB);
282   }
283
284   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i) {
285     SmallVector<BasicBlock*, 2> BlocksToExtractVec;
286     BlocksToExtractVec.push_back(BlocksToExtract[i]);
287     if (const InvokeInst *II =
288         dyn_cast<InvokeInst>(BlocksToExtract[i]->getTerminator()))
289       BlocksToExtractVec.push_back(II->getUnwindDest());
290     ExtractBasicBlock(BlocksToExtractVec);
291   }
292
293   return !BlocksToExtract.empty();
294 }