LoopExtractor.cpp 8.0 KB

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