LLVM API Documentation

PartialInlining.cpp

Go to the documentation of this file.
00001 //===- PartialInlining.cpp - Inline parts of functions --------------------===//
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 // This pass performs partial inlining, typically by inlining an if statement
00011 // that surrounds the body of the function.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "partialinlining"
00016 #include "llvm/Transforms/IPO.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Pass.h"
00020 #include "llvm/Analysis/Dominators.h"
00021 #include "llvm/Transforms/Utils/Cloning.h"
00022 #include "llvm/Transforms/Utils/FunctionUtils.h"
00023 #include "llvm/ADT/Statistic.h"
00024 #include "llvm/Support/Compiler.h"
00025 #include "llvm/Support/CFG.h"
00026 using namespace llvm;
00027 
00028 STATISTIC(NumPartialInlined, "Number of functions partially inlined");
00029 
00030 namespace {
00031   struct VISIBILITY_HIDDEN PartialInliner : public ModulePass {
00032     virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
00033     static char ID; // Pass identification, replacement for typeid
00034     PartialInliner() : ModulePass(&ID) {}
00035     
00036     bool runOnModule(Module& M);
00037     
00038   private:
00039     Function* unswitchFunction(Function* F);
00040   };
00041 }
00042 
00043 char PartialInliner::ID = 0;
00044 static RegisterPass<PartialInliner> X("partial-inliner", "Partial Inliner");
00045 
00046 ModulePass* llvm::createPartialInliningPass() { return new PartialInliner(); }
00047 
00048 Function* PartialInliner::unswitchFunction(Function* F) {
00049   // First, verify that this function is an unswitching candidate...
00050   BasicBlock* entryBlock = F->begin();
00051   if (!isa<BranchInst>(entryBlock->getTerminator()))
00052     return 0;
00053   
00054   BasicBlock* returnBlock = 0;
00055   BasicBlock* nonReturnBlock = 0;
00056   unsigned returnCount = 0;
00057   for (succ_iterator SI = succ_begin(entryBlock), SE = succ_end(entryBlock);
00058        SI != SE; ++SI)
00059     if (isa<ReturnInst>((*SI)->getTerminator())) {
00060       returnBlock = *SI;
00061       returnCount++;
00062     } else
00063       nonReturnBlock = *SI;
00064   
00065   if (returnCount != 1)
00066     return 0;
00067   
00068   // Clone the function, so that we can hack away on it.
00069   DenseMap<const Value*, Value*> ValueMap;
00070   Function* duplicateFunction = CloneFunction(F, ValueMap);
00071   duplicateFunction->setLinkage(GlobalValue::InternalLinkage);
00072   F->getParent()->getFunctionList().push_back(duplicateFunction);
00073   BasicBlock* newEntryBlock = cast<BasicBlock>(ValueMap[entryBlock]);
00074   BasicBlock* newReturnBlock = cast<BasicBlock>(ValueMap[returnBlock]);
00075   BasicBlock* newNonReturnBlock = cast<BasicBlock>(ValueMap[nonReturnBlock]);
00076   
00077   // Go ahead and update all uses to the duplicate, so that we can just
00078   // use the inliner functionality when we're done hacking.
00079   F->replaceAllUsesWith(duplicateFunction);
00080   
00081   // Special hackery is needed with PHI nodes that have inputs from more than
00082   // one extracted block.  For simplicity, just split the PHIs into a two-level
00083   // sequence of PHIs, some of which will go in the extracted region, and some
00084   // of which will go outside.
00085   BasicBlock* preReturn = newReturnBlock;
00086   newReturnBlock = newReturnBlock->splitBasicBlock(
00087                                               newReturnBlock->getFirstNonPHI());
00088   BasicBlock::iterator I = preReturn->begin();
00089   BasicBlock::iterator Ins = newReturnBlock->begin();
00090   while (I != preReturn->end()) {
00091     PHINode* OldPhi = dyn_cast<PHINode>(I);
00092     if (!OldPhi) break;
00093     
00094     PHINode* retPhi = PHINode::Create(OldPhi->getType(), "", Ins);
00095     OldPhi->replaceAllUsesWith(retPhi);
00096     Ins = newReturnBlock->getFirstNonPHI();
00097     
00098     retPhi->addIncoming(I, preReturn);
00099     retPhi->addIncoming(OldPhi->getIncomingValueForBlock(newEntryBlock),
00100                         newEntryBlock);
00101     OldPhi->removeIncomingValue(newEntryBlock);
00102     
00103     ++I;
00104   }
00105   newEntryBlock->getTerminator()->replaceUsesOfWith(preReturn, newReturnBlock);
00106   
00107   // Gather up the blocks that we're going to extract.
00108   std::vector<BasicBlock*> toExtract;
00109   toExtract.push_back(newNonReturnBlock);
00110   for (Function::iterator FI = duplicateFunction->begin(),
00111        FE = duplicateFunction->end(); FI != FE; ++FI)
00112     if (&*FI != newEntryBlock && &*FI != newReturnBlock &&
00113         &*FI != newNonReturnBlock)
00114       toExtract.push_back(FI);
00115       
00116   // The CodeExtractor needs a dominator tree.
00117   DominatorTree DT;
00118   DT.runOnFunction(*duplicateFunction);
00119   
00120   // Extract the body of the the if.
00121   Function* extractedFunction = ExtractCodeRegion(DT, toExtract);
00122   
00123   // Inline the top-level if test into all callers.
00124   std::vector<User*> Users(duplicateFunction->use_begin(), 
00125                            duplicateFunction->use_end());
00126   for (std::vector<User*>::iterator UI = Users.begin(), UE = Users.end();
00127        UI != UE; ++UI)
00128     if (CallInst* CI = dyn_cast<CallInst>(*UI))
00129       InlineFunction(CI);
00130     else if (InvokeInst* II = dyn_cast<InvokeInst>(*UI))
00131       InlineFunction(II);
00132   
00133   // Ditch the duplicate, since we're done with it, and rewrite all remaining
00134   // users (function pointers, etc.) back to the original function.
00135   duplicateFunction->replaceAllUsesWith(F);
00136   duplicateFunction->eraseFromParent();
00137   
00138   ++NumPartialInlined;
00139   
00140   return extractedFunction;
00141 }
00142 
00143 bool PartialInliner::runOnModule(Module& M) {
00144   std::vector<Function*> worklist;
00145   worklist.reserve(M.size());
00146   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
00147     if (!FI->use_empty() && !FI->isDeclaration())
00148     worklist.push_back(&*FI);
00149     
00150   bool changed = false;
00151   while (!worklist.empty()) {
00152     Function* currFunc = worklist.back();
00153     worklist.pop_back();
00154   
00155     if (currFunc->use_empty()) continue;
00156     
00157     bool recursive = false;
00158     for (Function::use_iterator UI = currFunc->use_begin(),
00159          UE = currFunc->use_end(); UI != UE; ++UI)
00160       if (Instruction* I = dyn_cast<Instruction>(UI))
00161         if (I->getParent()->getParent() == currFunc) {
00162           recursive = true;
00163           break;
00164         }
00165     if (recursive) continue;
00166           
00167     
00168     if (Function* newFunc = unswitchFunction(currFunc)) {
00169       worklist.push_back(newFunc);
00170       changed = true;
00171     }
00172     
00173   }
00174   
00175   return changed;
00176 }