LLVM API Documentation

LoopExtractor.cpp

Go to the documentation of this file.
00001 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
00011 // top-level loop into its own new function. If the loop is the ONLY loop in a
00012 // given function, it is not touched. This is a pass most useful for debugging
00013 // via bugpoint.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define DEBUG_TYPE "loop-extract"
00018 #include "llvm/Transforms/IPO.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/Pass.h"
00022 #include "llvm/Analysis/Dominators.h"
00023 #include "llvm/Analysis/LoopPass.h"
00024 #include "llvm/Support/CommandLine.h"
00025 #include "llvm/Transforms/Scalar.h"
00026 #include "llvm/Transforms/Utils/FunctionUtils.h"
00027 #include "llvm/ADT/Statistic.h"
00028 #include <fstream>
00029 #include <set>
00030 using namespace llvm;
00031 
00032 STATISTIC(NumExtracted, "Number of loops extracted");
00033 
00034 namespace {
00035   struct LoopExtractor : public LoopPass {
00036     static char ID; // Pass identification, replacement for typeid
00037     unsigned NumLoops;
00038 
00039     explicit LoopExtractor(unsigned numLoops = ~0) 
00040       : LoopPass(ID), NumLoops(numLoops) {
00041         initializeLoopExtractorPass(*PassRegistry::getPassRegistry());
00042       }
00043 
00044     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
00045 
00046     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00047       AU.addRequiredID(BreakCriticalEdgesID);
00048       AU.addRequiredID(LoopSimplifyID);
00049       AU.addRequired<DominatorTree>();
00050     }
00051   };
00052 }
00053 
00054 char LoopExtractor::ID = 0;
00055 INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract",
00056                 "Extract loops into new functions", false, false)
00057 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
00058 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00059 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
00060 INITIALIZE_PASS_END(LoopExtractor, "loop-extract",
00061                 "Extract loops into new functions", false, false)
00062 
00063 namespace {
00064   /// SingleLoopExtractor - For bugpoint.
00065   struct SingleLoopExtractor : public LoopExtractor {
00066     static char ID; // Pass identification, replacement for typeid
00067     SingleLoopExtractor() : LoopExtractor(1) {}
00068   };
00069 } // End anonymous namespace
00070 
00071 char SingleLoopExtractor::ID = 0;
00072 INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single",
00073                 "Extract at most one loop into a new function", false, false)
00074 
00075 // createLoopExtractorPass - This pass extracts all natural loops from the
00076 // program into a function if it can.
00077 //
00078 Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); }
00079 
00080 bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) {
00081   // Only visit top-level loops.
00082   if (L->getParentLoop())
00083     return false;
00084 
00085   // If LoopSimplify form is not available, stay out of trouble.
00086   if (!L->isLoopSimplifyForm())
00087     return false;
00088 
00089   DominatorTree &DT = getAnalysis<DominatorTree>();
00090   bool Changed = false;
00091 
00092   // If there is more than one top-level loop in this function, extract all of
00093   // the loops. Otherwise there is exactly one top-level loop; in this case if
00094   // this function is more than a minimal wrapper around the loop, extract
00095   // the loop.
00096   bool ShouldExtractLoop = false;
00097 
00098   // Extract the loop if the entry block doesn't branch to the loop header.
00099   TerminatorInst *EntryTI =
00100     L->getHeader()->getParent()->getEntryBlock().getTerminator();
00101   if (!isa<BranchInst>(EntryTI) ||
00102       !cast<BranchInst>(EntryTI)->isUnconditional() ||
00103       EntryTI->getSuccessor(0) != L->getHeader())
00104     ShouldExtractLoop = true;
00105   else {
00106     // Check to see if any exits from the loop are more than just return
00107     // blocks.
00108     SmallVector<BasicBlock*, 8> ExitBlocks;
00109     L->getExitBlocks(ExitBlocks);
00110     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00111       if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) {
00112         ShouldExtractLoop = true;
00113         break;
00114       }
00115   }
00116   if (ShouldExtractLoop) {
00117     if (NumLoops == 0) return Changed;
00118     --NumLoops;
00119     if (ExtractLoop(DT, L) != 0) {
00120       Changed = true;
00121       // After extraction, the loop is replaced by a function call, so
00122       // we shouldn't try to run any more loop passes on it.
00123       LPM.deleteLoopFromQueue(L);
00124     }
00125     ++NumExtracted;
00126   }
00127 
00128   return Changed;
00129 }
00130 
00131 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
00132 // program into a function if it can.  This is used by bugpoint.
00133 //
00134 Pass *llvm::createSingleLoopExtractorPass() {
00135   return new SingleLoopExtractor();
00136 }
00137 
00138 
00139 // BlockFile - A file which contains a list of blocks that should not be
00140 // extracted.
00141 static cl::opt<std::string>
00142 BlockFile("extract-blocks-file", cl::value_desc("filename"),
00143           cl::desc("A file containing list of basic blocks to not extract"),
00144           cl::Hidden);
00145 
00146 namespace {
00147   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
00148   /// from the module into their own functions except for those specified by the
00149   /// BlocksToNotExtract list.
00150   class BlockExtractorPass : public ModulePass {
00151     void LoadFile(const char *Filename);
00152 
00153     std::vector<BasicBlock*> BlocksToNotExtract;
00154     std::vector<std::pair<std::string, std::string> > BlocksToNotExtractByName;
00155   public:
00156     static char ID; // Pass identification, replacement for typeid
00157     BlockExtractorPass() : ModulePass(ID) {
00158       if (!BlockFile.empty())
00159         LoadFile(BlockFile.c_str());
00160     }
00161 
00162     bool runOnModule(Module &M);
00163   };
00164 }
00165 
00166 char BlockExtractorPass::ID = 0;
00167 INITIALIZE_PASS(BlockExtractorPass, "extract-blocks",
00168                 "Extract Basic Blocks From Module (for bugpoint use)",
00169                 false, false)
00170 
00171 // createBlockExtractorPass - This pass extracts all blocks (except those
00172 // specified in the argument list) from the functions in the module.
00173 //
00174 ModulePass *llvm::createBlockExtractorPass()
00175 {
00176   return new BlockExtractorPass();
00177 }
00178 
00179 void BlockExtractorPass::LoadFile(const char *Filename) {
00180   // Load the BlockFile...
00181   std::ifstream In(Filename);
00182   if (!In.good()) {
00183     errs() << "WARNING: BlockExtractor couldn't load file '" << Filename
00184            << "'!\n";
00185     return;
00186   }
00187   while (In) {
00188     std::string FunctionName, BlockName;
00189     In >> FunctionName;
00190     In >> BlockName;
00191     if (!BlockName.empty())
00192       BlocksToNotExtractByName.push_back(
00193           std::make_pair(FunctionName, BlockName));
00194   }
00195 }
00196 
00197 bool BlockExtractorPass::runOnModule(Module &M) {
00198   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
00199   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
00200     BasicBlock *BB = BlocksToNotExtract[i];
00201     Function *F = BB->getParent();
00202 
00203     // Map the corresponding function in this module.
00204     Function *MF = M.getFunction(F->getName());
00205     assert(MF->getFunctionType() == F->getFunctionType() && "Wrong function?");
00206 
00207     // Figure out which index the basic block is in its function.
00208     Function::iterator BBI = MF->begin();
00209     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
00210     TranslatedBlocksToNotExtract.insert(BBI);
00211   }
00212 
00213   while (!BlocksToNotExtractByName.empty()) {
00214     // There's no way to find BBs by name without looking at every BB inside
00215     // every Function. Fortunately, this is always empty except when used by
00216     // bugpoint in which case correctness is more important than performance.
00217 
00218     std::string &FuncName  = BlocksToNotExtractByName.back().first;
00219     std::string &BlockName = BlocksToNotExtractByName.back().second;
00220 
00221     for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
00222       Function &F = *FI;
00223       if (F.getName() != FuncName) continue;
00224 
00225       for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
00226         BasicBlock &BB = *BI;
00227         if (BB.getName() != BlockName) continue;
00228 
00229         TranslatedBlocksToNotExtract.insert(BI);
00230       }
00231     }
00232 
00233     BlocksToNotExtractByName.pop_back();
00234   }
00235 
00236   // Now that we know which blocks to not extract, figure out which ones we WANT
00237   // to extract.
00238   std::vector<BasicBlock*> BlocksToExtract;
00239   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
00240     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00241       if (!TranslatedBlocksToNotExtract.count(BB))
00242         BlocksToExtract.push_back(BB);
00243 
00244   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
00245     ExtractBasicBlock(BlocksToExtract[i]);
00246 
00247   return !BlocksToExtract.empty();
00248 }