Fix batch of converting RegisterPass<> to INTIALIZE_PASS().
[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/FunctionUtils.h"
27 #include "llvm/ADT/Statistic.h"
28 #include <fstream>
29 #include <set>
30 using namespace llvm;
31
32 STATISTIC(NumExtracted, "Number of loops extracted");
33
34 namespace {
35   struct LoopExtractor : public LoopPass {
36     static char ID; // Pass identification, replacement for typeid
37     unsigned NumLoops;
38
39     explicit LoopExtractor(unsigned numLoops = ~0) 
40       : LoopPass(&ID), NumLoops(numLoops) {}
41
42     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
43
44     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45       AU.addRequiredID(BreakCriticalEdgesID);
46       AU.addRequiredID(LoopSimplifyID);
47       AU.addRequired<DominatorTree>();
48     }
49   };
50 }
51
52 char LoopExtractor::ID = 0;
53 INITIALIZE_PASS(LoopExtractor, "loop-extract",
54                 "Extract loops into new functions", false, false);
55
56 namespace {
57   /// SingleLoopExtractor - For bugpoint.
58   struct SingleLoopExtractor : public LoopExtractor {
59     static char ID; // Pass identification, replacement for typeid
60     SingleLoopExtractor() : LoopExtractor(1) {}
61   };
62 } // End anonymous namespace
63
64 char SingleLoopExtractor::ID = 0;
65 INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
66                 "Extract at most one loop into a new function", false, false);
67
68 // createLoopExtractorPass - This pass extracts all natural loops from the
69 // program into a function if it can.
70 //
71 Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
72
73 bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
74   // Only visit top-level loops.
75   if (L->getParentLoop())
76     return false;
77
78   // If LoopSimplify form is not available, stay out of trouble.
79   if (!L->isLoopSimplifyForm())
80     return false;
81
82   DominatorTree &DT = getAnalysis<DominatorTree>();
83   bool Changed = false;
84
85   // If there is more than one top-level loop in this function, extract all of
86   // the loops. Otherwise there is exactly one top-level loop; in this case if
87   // this function is more than a minimal wrapper around the loop, extract
88   // the loop.
89   bool ShouldExtractLoop = false;
90
91   // Extract the loop if the entry block doesn't branch to the loop header.
92   TerminatorInst *EntryTI =
93     L->getHeader()->getParent()->getEntryBlock().getTerminator();
94   if (!isa<BranchInst>(EntryTI) ||
95       !cast<BranchInst>(EntryTI)->isUnconditional() ||
96       EntryTI->getSuccessor(0) != L->getHeader())
97     ShouldExtractLoop = true;
98   else {
99     // Check to see if any exits from the loop are more than just return
100     // blocks.
101     SmallVector<BasicBlock*, 8> ExitBlocks;
102     L->getExitBlocks(ExitBlocks);
103     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
104       if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
105         ShouldExtractLoop = true;
106         break;
107       }
108   }
109   if (ShouldExtractLoop) {
110     if (NumLoops == 0) return Changed;
111     --NumLoops;
112     if (ExtractLoop(DT, L) != 0) {
113       Changed = true;
114       // After extraction, the loop is replaced by a function call, so
115       // we shouldn't try to run any more loop passes on it.
116       LPM.deleteLoopFromQueue(L);
117     }
118     ++NumExtracted;
119   }
120
121   return Changed;
122 }
123
124 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
125 // program into a function if it can.  This is used by bugpoint.
126 //
127 Pass *llvm::createSingleLoopExtractorPass() {
128   return new SingleLoopExtractor();
129 }
130
131
132 // BlockFile - A file which contains a list of blocks that should not be
133 // extracted.
134 static cl::opt<std::string>
135 BlockFile("extract-blocks-file", cl::value_desc("filename"),
136           cl::desc("A file containing list of basic blocks to not extract"),
137           cl::Hidden);
138
139 namespace {
140   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
141   /// from the module into their own functions except for those specified by the
142   /// BlocksToNotExtract list.
143   class BlockExtractorPass : public ModulePass {
144     void LoadFile(const char *Filename);
145
146     std::vector<BasicBlock*> BlocksToNotExtract;
147     std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
148   public:
149     static char ID; // Pass identification, replacement for typeid
150     explicit BlockExtractorPass(const std::vector<BasicBlock*> &B) 
151       : ModulePass(&ID), BlocksToNotExtract(B) {
152       if (!BlockFile.empty())
153         LoadFile(BlockFile.c_str());
154     }
155     BlockExtractorPass() : ModulePass(&ID) {}
156
157     bool runOnModule(Module &M);
158   };
159 }
160
161 char BlockExtractorPass::ID = 0;
162 INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
163                 "Extract Basic Blocks From Module (for bugpoint use)",
164                 false, false);
165
166 // createBlockExtractorPass - This pass extracts all blocks (except those
167 // specified in the argument list) from the functions in the module.
168 //
169 ModulePass *llvm::createBlockExtractorPass(const std::vector<BasicBlock*> &BTNE)
170 {
171   return new BlockExtractorPass(BTNE);
172 }
173
174 void BlockExtractorPass::LoadFile(const char *Filename) {
175   // Load the BlockFile...
176   std::ifstream In(Filename);
177   if (!In.good()) {
178     errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
179            << "'!\n";
180     return;
181   }
182   while (In) {
183     std::string FunctionName, BlockName;
184     In >> FunctionName;
185     In >> BlockName;
186     if (!BlockName.empty())
187       BlocksToNotExtractByName.push_back(
188           std::make_pair(FunctionName, BlockName));
189   }
190 }
191
192 bool BlockExtractorPass::runOnModule(Module &M) {
193   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
194   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
195     BasicBlock *BB = BlocksToNotExtract[i];
196     Function *F = BB->getParent();
197
198     // Map the corresponding function in this module.
199     Function *MF = M.getFunction(F->getName());
200     assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
201
202     // Figure out which index the basic block is in its function.
203     Function::iterator BBI = MF->begin();
204     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
205     TranslatedBlocksToNotExtract.insert(BBI);
206   }
207
208   while (!BlocksToNotExtractByName.empty()) {
209     // There's no way to find BBs by name without looking at every BB inside
210     // every Function. Fortunately, this is always empty except when used by
211     // bugpoint in which case correctness is more important than performance.
212
213     std::string &FuncName  = BlocksToNotExtractByName.back().first;
214     std::string &BlockName = BlocksToNotExtractByName.back().second;
215
216     for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
217       Function &F = *FI;
218       if (F.getName() != FuncName) continue;
219
220       for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
221         BasicBlock &BB = *BI;
222         if (BB.getName() != BlockName) continue;
223
224         TranslatedBlocksToNotExtract.insert(BI);
225       }
226     }
227
228     BlocksToNotExtractByName.pop_back();
229   }
230
231   // Now that we know which blocks to not extract, figure out which ones we WANT
232   // to extract.
233   std::vector<BasicBlock*> BlocksToExtract;
234   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
235     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
236       if (!TranslatedBlocksToNotExtract.count(BB))
237         BlocksToExtract.push_back(BB);
238
239   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
240     ExtractBasicBlock(BlocksToExtract[i]);
241
242   return !BlocksToExtract.empty();
243 }