173a6bdd9SChris Lattner //===- ExtractFunction.cpp - Extract a function from Program --------------===//
273a6bdd9SChris Lattner //
309344dcfSJohn Criswell //                     The LLVM Compiler Infrastructure
409344dcfSJohn Criswell //
509344dcfSJohn Criswell // This file was developed by the LLVM research group and is distributed under
609344dcfSJohn Criswell // the University of Illinois Open Source License. See LICENSE.TXT for details.
709344dcfSJohn Criswell //
809344dcfSJohn Criswell //===----------------------------------------------------------------------===//
909344dcfSJohn Criswell //
10fd72bed3SChris Lattner // This file implements several methods that are used to extract functions,
11fd72bed3SChris Lattner // loops, or portions of a module from the rest of the module.
1273a6bdd9SChris Lattner //
1373a6bdd9SChris Lattner //===----------------------------------------------------------------------===//
1473a6bdd9SChris Lattner 
1573a6bdd9SChris Lattner #include "BugDriver.h"
160c2305b1SMisha Brukman #include "llvm/Constant.h"
1773a6bdd9SChris Lattner #include "llvm/Module.h"
1873a6bdd9SChris Lattner #include "llvm/PassManager.h"
19ef432703SBrian Gaeke #include "llvm/Pass.h"
200c2305b1SMisha Brukman #include "llvm/Type.h"
210c2305b1SMisha Brukman #include "llvm/Analysis/Verifier.h"
2273a6bdd9SChris Lattner #include "llvm/Transforms/IPO.h"
230eb5ce94SChris Lattner #include "llvm/Transforms/Scalar.h"
2473a6bdd9SChris Lattner #include "llvm/Transforms/Utils/Cloning.h"
25a060b10eSChris Lattner #include "llvm/Transforms/Utils/FunctionUtils.h"
26f3e8f97dSChris Lattner #include "llvm/Target/TargetData.h"
277c16caa3SReid Spencer #include "llvm/Support/CommandLine.h"
287c16caa3SReid Spencer #include "llvm/Support/Debug.h"
297c16caa3SReid Spencer #include "llvm/Support/FileUtilities.h"
303838243dSChris Lattner #include <set>
313f1ad878SChris Lattner using namespace llvm;
32960707c3SBrian Gaeke 
33960707c3SBrian Gaeke namespace llvm {
34d1e2aaefSChris Lattner   bool DisableSimplifyCFG = false;
35960707c3SBrian Gaeke } // End llvm namespace
36960707c3SBrian Gaeke 
378d8de422SChris Lattner namespace {
388d8de422SChris Lattner   cl::opt<bool>
398d8de422SChris Lattner   NoDCE ("disable-dce",
408d8de422SChris Lattner          cl::desc("Do not use the -dce pass to reduce testcases"));
41d1e2aaefSChris Lattner   cl::opt<bool, true>
42d1e2aaefSChris Lattner   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
438d8de422SChris Lattner          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
448d8de422SChris Lattner }
4573a6bdd9SChris Lattner 
460eb5ce94SChris Lattner /// deleteInstructionFromProgram - This method clones the current Program and
470eb5ce94SChris Lattner /// deletes the specified instruction from the cloned module.  It then runs a
480eb5ce94SChris Lattner /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
490eb5ce94SChris Lattner /// depends on the value.  The modified module is then returned.
500eb5ce94SChris Lattner ///
51b943b6b0SChris Lattner Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
520eb5ce94SChris Lattner                                                 unsigned Simplification) const {
530eb5ce94SChris Lattner   Module *Result = CloneModule(Program);
540eb5ce94SChris Lattner 
55b943b6b0SChris Lattner   const BasicBlock *PBB = I->getParent();
56b943b6b0SChris Lattner   const Function *PF = PBB->getParent();
570eb5ce94SChris Lattner 
580eb5ce94SChris Lattner   Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
59b943b6b0SChris Lattner   std::advance(RFI, std::distance(PF->getParent()->begin(),
60b943b6b0SChris Lattner                                   Module::const_iterator(PF)));
610eb5ce94SChris Lattner 
620eb5ce94SChris Lattner   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
63b943b6b0SChris Lattner   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
640eb5ce94SChris Lattner 
650eb5ce94SChris Lattner   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
66b943b6b0SChris Lattner   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
67b943b6b0SChris Lattner   Instruction *TheInst = RI;              // Got the corresponding instruction!
680eb5ce94SChris Lattner 
690eb5ce94SChris Lattner   // If this instruction produces a value, replace any users with null values
70b943b6b0SChris Lattner   if (TheInst->getType() != Type::VoidTy)
71b943b6b0SChris Lattner     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
720eb5ce94SChris Lattner 
730eb5ce94SChris Lattner   // Remove the instruction from the program.
74b943b6b0SChris Lattner   TheInst->getParent()->getInstList().erase(TheInst);
750eb5ce94SChris Lattner 
7610c0469bSChris Lattner   // Spiff up the output a little bit.
770eb5ce94SChris Lattner   PassManager Passes;
78f3e8f97dSChris Lattner   // Make sure that the appropriate target data is always used...
79f3e8f97dSChris Lattner   Passes.add(new TargetData("bugpoint", Result));
80f3e8f97dSChris Lattner 
81fd72bed3SChris Lattner   /// FIXME: If this used runPasses() like the methods below, we could get rid
82fd72bed3SChris Lattner   /// of the -disable-* options!
838d8de422SChris Lattner   if (Simplification > 1 && !NoDCE)
840eb5ce94SChris Lattner     Passes.add(createDeadCodeEliminationPass());
85d1e2aaefSChris Lattner   if (Simplification && !DisableSimplifyCFG)
860eb5ce94SChris Lattner     Passes.add(createCFGSimplificationPass());      // Delete dead control flow
8744ffd7c3SChris Lattner 
8844ffd7c3SChris Lattner   Passes.add(createVerifierPass());
890eb5ce94SChris Lattner   Passes.run(*Result);
900eb5ce94SChris Lattner   return Result;
910eb5ce94SChris Lattner }
92514c02ebSChris Lattner 
932920100eSChris Lattner static const PassInfo *getPI(Pass *P) {
942920100eSChris Lattner   const PassInfo *PI = P->getPassInfo();
952920100eSChris Lattner   delete P;
962920100eSChris Lattner   return PI;
972920100eSChris Lattner }
982920100eSChris Lattner 
99514c02ebSChris Lattner /// performFinalCleanups - This method clones the current Program and performs
100514c02ebSChris Lattner /// a series of cleanups intended to get rid of extra cruft on the module
101*5e166a5fSChris Lattner /// before handing it to the user.
102514c02ebSChris Lattner ///
1032920100eSChris Lattner Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
1042b3ab562SChris Lattner   // Make all functions external, so GlobalDCE doesn't delete them...
1052b3ab562SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
1062b3ab562SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
1072b3ab562SChris Lattner 
1082920100eSChris Lattner   std::vector<const PassInfo*> CleanupPasses;
1092920100eSChris Lattner   CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
1102920100eSChris Lattner   CleanupPasses.push_back(getPI(createGlobalDCEPass()));
1112920100eSChris Lattner   CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
1123f1ad878SChris Lattner 
1133f1ad878SChris Lattner   if (MayModifySemantics)
1142920100eSChris Lattner     CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
1153f1ad878SChris Lattner   else
1163f1ad878SChris Lattner     CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
1172920100eSChris Lattner 
1186ce2d033SChris Lattner   Module *New = runPassesOn(M, CleanupPasses);
1196ce2d033SChris Lattner   if (New == 0) {
1203fe96bc9SChris Lattner     std::cerr << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
121*5e166a5fSChris Lattner     return M;
1226ce2d033SChris Lattner   }
1232920100eSChris Lattner   delete M;
1246ce2d033SChris Lattner   return New;
125514c02ebSChris Lattner }
126567543f0SChris Lattner 
127567543f0SChris Lattner 
1283fe96bc9SChris Lattner /// ExtractLoop - Given a module, extract up to one loop from it into a new
1293fe96bc9SChris Lattner /// function.  This returns null if there are no extractable loops in the
1303fe96bc9SChris Lattner /// program or if the loop extractor crashes.
1313fe96bc9SChris Lattner Module *BugDriver::ExtractLoop(Module *M) {
1323fe96bc9SChris Lattner   std::vector<const PassInfo*> LoopExtractPasses;
1333fe96bc9SChris Lattner   LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
1343fe96bc9SChris Lattner 
1356ce2d033SChris Lattner   Module *NewM = runPassesOn(M, LoopExtractPasses);
1366ce2d033SChris Lattner   if (NewM == 0) {
137bcec7875SChris Lattner     Module *Old = swapProgramIn(M);
138bcec7875SChris Lattner     std::cout << "*** Loop extraction failed: ";
139bcec7875SChris Lattner     EmitProgressBytecode("loopextraction", true);
140bcec7875SChris Lattner     std::cout << "*** Sorry. :(  Please report a bug!\n";
141bcec7875SChris Lattner     swapProgramIn(Old);
1423fe96bc9SChris Lattner     return 0;
1433fe96bc9SChris Lattner   }
1443fe96bc9SChris Lattner 
1453fe96bc9SChris Lattner   // Check to see if we created any new functions.  If not, no loops were
1468cb483b3SChris Lattner   // extracted and we should return null.  Limit the number of loops we extract
1478cb483b3SChris Lattner   // to avoid taking forever.
1488cb483b3SChris Lattner   static unsigned NumExtracted = 32;
149d308797cSChris Lattner   if (M->size() == NewM->size() || --NumExtracted == 0) {
1503fe96bc9SChris Lattner     delete NewM;
1513fe96bc9SChris Lattner     return 0;
152d308797cSChris Lattner   } else {
153d308797cSChris Lattner     assert(M->size() < NewM->size() && "Loop extract removed functions?");
154d308797cSChris Lattner     Module::iterator MI = NewM->begin();
155d308797cSChris Lattner     for (unsigned i = 0, e = M->size(); i != e; ++i)
156d308797cSChris Lattner       ++MI;
1573fe96bc9SChris Lattner   }
1583fe96bc9SChris Lattner 
1593fe96bc9SChris Lattner   return NewM;
1603fe96bc9SChris Lattner }
1613fe96bc9SChris Lattner 
1623fe96bc9SChris Lattner 
163567543f0SChris Lattner // DeleteFunctionBody - "Remove" the function by deleting all of its basic
164567543f0SChris Lattner // blocks, making it external.
165567543f0SChris Lattner //
166567543f0SChris Lattner void llvm::DeleteFunctionBody(Function *F) {
167567543f0SChris Lattner   // delete the body of the function...
168567543f0SChris Lattner   F->deleteBody();
169567543f0SChris Lattner   assert(F->isExternal() && "This didn't make the function external!");
170567543f0SChris Lattner }
171567543f0SChris Lattner 
172567543f0SChris Lattner /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
173567543f0SChris Lattner /// module, split the functions OUT of the specified module, and place them in
174567543f0SChris Lattner /// the new module.
1755a5e414bSChris Lattner ///
1765a5e414bSChris Lattner /// FIXME: this could be made DRAMATICALLY more efficient for large programs if
1775a5e414bSChris Lattner /// we just MOVED functions from one module to the other, instead of cloning the
1785a5e414bSChris Lattner /// whole module, then proceeding to delete an entire module's worth of stuff.
1795a5e414bSChris Lattner ///
180567543f0SChris Lattner Module *llvm::SplitFunctionsOutOfModule(Module *M,
181567543f0SChris Lattner                                         const std::vector<Function*> &F) {
182567543f0SChris Lattner   // Make sure functions & globals are all external so that linkage
183567543f0SChris Lattner   // between the two modules will work.
184567543f0SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
185567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
186567543f0SChris Lattner   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
187567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
188567543f0SChris Lattner 
189567543f0SChris Lattner   Module *New = CloneModule(M);
190567543f0SChris Lattner 
191567543f0SChris Lattner   // Make sure global initializers exist only in the safe module (CBE->.so)
192567543f0SChris Lattner   for (Module::giterator I = New->gbegin(), E = New->gend(); I != E; ++I)
193567543f0SChris Lattner     I->setInitializer(0);  // Delete the initializer to make it external
194567543f0SChris Lattner 
195567543f0SChris Lattner   // Remove the Test functions from the Safe module
1963838243dSChris Lattner   std::set<std::pair<std::string, const PointerType*> > TestFunctions;
197567543f0SChris Lattner   for (unsigned i = 0, e = F.size(); i != e; ++i) {
1983838243dSChris Lattner     TestFunctions.insert(std::make_pair(F[i]->getName(), F[i]->getType()));
199567543f0SChris Lattner     Function *TNOF = M->getFunction(F[i]->getName(), F[i]->getFunctionType());
200567543f0SChris Lattner     DEBUG(std::cerr << "Removing function " << F[i]->getName() << "\n");
201567543f0SChris Lattner     assert(TNOF && "Function doesn't exist in module!");
202567543f0SChris Lattner     DeleteFunctionBody(TNOF);       // Function is now external in this module!
203567543f0SChris Lattner   }
204567543f0SChris Lattner 
205567543f0SChris Lattner   // Remove the Safe functions from the Test module
2063838243dSChris Lattner   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
2073838243dSChris Lattner     if (!TestFunctions.count(std::make_pair(I->getName(), I->getType())))
208567543f0SChris Lattner       DeleteFunctionBody(I);
209567543f0SChris Lattner   return New;
210567543f0SChris Lattner }
211a060b10eSChris Lattner 
212a060b10eSChris Lattner //===----------------------------------------------------------------------===//
213a060b10eSChris Lattner // Basic Block Extraction Code
214a060b10eSChris Lattner //===----------------------------------------------------------------------===//
215a060b10eSChris Lattner 
216a060b10eSChris Lattner namespace {
217a060b10eSChris Lattner   std::vector<BasicBlock*> BlocksToNotExtract;
218a060b10eSChris Lattner 
219a060b10eSChris Lattner   /// BlockExtractorPass - This pass is used by bugpoint to extract all blocks
220a060b10eSChris Lattner   /// from the module into their own functions except for those specified by the
221a060b10eSChris Lattner   /// BlocksToNotExtract list.
2224f2cf030SChris Lattner   class BlockExtractorPass : public ModulePass {
2234f2cf030SChris Lattner     bool runOnModule(Module &M);
224a060b10eSChris Lattner   };
225a060b10eSChris Lattner   RegisterOpt<BlockExtractorPass>
226a060b10eSChris Lattner   XX("extract-bbs", "Extract Basic Blocks From Module (for bugpoint use)");
227a060b10eSChris Lattner }
228a060b10eSChris Lattner 
2294f2cf030SChris Lattner bool BlockExtractorPass::runOnModule(Module &M) {
230a060b10eSChris Lattner   std::set<BasicBlock*> TranslatedBlocksToNotExtract;
231a060b10eSChris Lattner   for (unsigned i = 0, e = BlocksToNotExtract.size(); i != e; ++i) {
232a060b10eSChris Lattner     BasicBlock *BB = BlocksToNotExtract[i];
233a060b10eSChris Lattner     Function *F = BB->getParent();
234a060b10eSChris Lattner 
235a060b10eSChris Lattner     // Map the corresponding function in this module.
236a060b10eSChris Lattner     Function *MF = M.getFunction(F->getName(), F->getFunctionType());
237a060b10eSChris Lattner 
238a060b10eSChris Lattner     // Figure out which index the basic block is in its function.
239a060b10eSChris Lattner     Function::iterator BBI = MF->begin();
240a060b10eSChris Lattner     std::advance(BBI, std::distance(F->begin(), Function::iterator(BB)));
241a060b10eSChris Lattner     TranslatedBlocksToNotExtract.insert(BBI);
242a060b10eSChris Lattner   }
243a060b10eSChris Lattner 
244a060b10eSChris Lattner   // Now that we know which blocks to not extract, figure out which ones we WANT
245a060b10eSChris Lattner   // to extract.
246a060b10eSChris Lattner   std::vector<BasicBlock*> BlocksToExtract;
247a060b10eSChris Lattner   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
248a060b10eSChris Lattner     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
249a060b10eSChris Lattner       if (!TranslatedBlocksToNotExtract.count(BB))
250a060b10eSChris Lattner         BlocksToExtract.push_back(BB);
251a060b10eSChris Lattner 
252a060b10eSChris Lattner   for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
253a060b10eSChris Lattner     ExtractBasicBlock(BlocksToExtract[i]);
254a060b10eSChris Lattner 
255a060b10eSChris Lattner   return !BlocksToExtract.empty();
256a060b10eSChris Lattner }
257a060b10eSChris Lattner 
258a060b10eSChris Lattner /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
259a060b10eSChris Lattner /// into their own functions.  The only detail is that M is actually a module
260a060b10eSChris Lattner /// cloned from the one the BBs are in, so some mapping needs to be performed.
261a060b10eSChris Lattner /// If this operation fails for some reason (ie the implementation is buggy),
262a060b10eSChris Lattner /// this function should return null, otherwise it returns a new Module.
263a060b10eSChris Lattner Module *BugDriver::ExtractMappedBlocksFromModule(const
264a060b10eSChris Lattner                                                  std::vector<BasicBlock*> &BBs,
265a060b10eSChris Lattner                                                  Module *M) {
266a060b10eSChris Lattner   // Set the global list so that pass will be able to access it.
267a060b10eSChris Lattner   BlocksToNotExtract = BBs;
268a060b10eSChris Lattner 
269a060b10eSChris Lattner   std::vector<const PassInfo*> PI;
270a060b10eSChris Lattner   PI.push_back(getPI(new BlockExtractorPass()));
271a060b10eSChris Lattner   Module *Ret = runPassesOn(M, PI);
272a060b10eSChris Lattner   BlocksToNotExtract.clear();
273af32dfa0SChris Lattner   if (Ret == 0) {
274a060b10eSChris Lattner     std::cout << "*** Basic Block extraction failed, please report a bug!\n";
275af32dfa0SChris Lattner     M = swapProgramIn(M);
276af32dfa0SChris Lattner     EmitProgressBytecode("basicblockextractfail", true);
277af32dfa0SChris Lattner     M = swapProgramIn(M);
278af32dfa0SChris Lattner   }
279a060b10eSChris Lattner   return Ret;
280a060b10eSChris Lattner }
281