ExtractFunction.cpp revision 7fa44fca308a0f8d13d981c2460ddb6de5a7b667
1//===- ExtractFunction.cpp - Extract a function from Program --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements several methods that are used to extract functions,
11// loops, or portions of a module from the rest of the module.
12//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
16#include "llvm/Constant.h"
17#include "llvm/Module.h"
18#include "llvm/PassManager.h"
19#include "llvm/Pass.h"
20#include "llvm/Type.h"
21#include "llvm/Analysis/Verifier.h"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Transforms/Utils/Cloning.h"
25#include "llvm/Target/TargetData.h"
26#include "Support/CommandLine.h"
27#include "Support/Debug.h"
28#include "Support/FileUtilities.h"
29using namespace llvm;
30
31namespace llvm {
32  bool DisableSimplifyCFG = false;
33} // End llvm namespace
34
35namespace {
36  cl::opt<bool>
37  NoDCE ("disable-dce",
38         cl::desc("Do not use the -dce pass to reduce testcases"));
39  cl::opt<bool, true>
40  NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
41         cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
42}
43
44/// deleteInstructionFromProgram - This method clones the current Program and
45/// deletes the specified instruction from the cloned module.  It then runs a
46/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
47/// depends on the value.  The modified module is then returned.
48///
49Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
50                                                unsigned Simplification) const {
51  Module *Result = CloneModule(Program);
52
53  const BasicBlock *PBB = I->getParent();
54  const Function *PF = PBB->getParent();
55
56  Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
57  std::advance(RFI, std::distance(PF->getParent()->begin(),
58                                  Module::const_iterator(PF)));
59
60  Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
61  std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
62
63  BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
64  std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
65  Instruction *TheInst = RI;              // Got the corresponding instruction!
66
67  // If this instruction produces a value, replace any users with null values
68  if (TheInst->getType() != Type::VoidTy)
69    TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
70
71  // Remove the instruction from the program.
72  TheInst->getParent()->getInstList().erase(TheInst);
73
74  // Spiff up the output a little bit.
75  PassManager Passes;
76  // Make sure that the appropriate target data is always used...
77  Passes.add(new TargetData("bugpoint", Result));
78
79  /// FIXME: If this used runPasses() like the methods below, we could get rid
80  /// of the -disable-* options!
81  if (Simplification > 1 && !NoDCE)
82    Passes.add(createDeadCodeEliminationPass());
83  if (Simplification && !DisableSimplifyCFG)
84    Passes.add(createCFGSimplificationPass());      // Delete dead control flow
85
86  Passes.add(createVerifierPass());
87  Passes.run(*Result);
88  return Result;
89}
90
91static const PassInfo *getPI(Pass *P) {
92  const PassInfo *PI = P->getPassInfo();
93  delete P;
94  return PI;
95}
96
97/// performFinalCleanups - This method clones the current Program and performs
98/// a series of cleanups intended to get rid of extra cruft on the module
99/// before handing it to the user...
100///
101Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
102  // Make all functions external, so GlobalDCE doesn't delete them...
103  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
104    I->setLinkage(GlobalValue::ExternalLinkage);
105
106  std::vector<const PassInfo*> CleanupPasses;
107  CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
108  CleanupPasses.push_back(getPI(createGlobalDCEPass()));
109  CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
110
111  if (MayModifySemantics)
112    CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
113  else
114    CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
115
116  Module *New = runPassesOn(M, CleanupPasses);
117  if (New == 0) {
118    std::cerr << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
119  }
120  delete M;
121  return New;
122}
123
124
125/// ExtractLoop - Given a module, extract up to one loop from it into a new
126/// function.  This returns null if there are no extractable loops in the
127/// program or if the loop extractor crashes.
128Module *BugDriver::ExtractLoop(Module *M) {
129  std::vector<const PassInfo*> LoopExtractPasses;
130  LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
131
132  Module *NewM = runPassesOn(M, LoopExtractPasses);
133  if (NewM == 0) {
134    Module *Old = swapProgramIn(M);
135    std::cout << "*** Loop extraction failed: ";
136    EmitProgressBytecode("loopextraction", true);
137    std::cout << "*** Sorry. :(  Please report a bug!\n";
138    swapProgramIn(Old);
139    return 0;
140  }
141
142  // Check to see if we created any new functions.  If not, no loops were
143  // extracted and we should return null.
144  if (M->size() == NewM->size()) {
145    delete NewM;
146    return 0;
147  }
148
149  return NewM;
150}
151
152
153// DeleteFunctionBody - "Remove" the function by deleting all of its basic
154// blocks, making it external.
155//
156void llvm::DeleteFunctionBody(Function *F) {
157  // delete the body of the function...
158  F->deleteBody();
159  assert(F->isExternal() && "This didn't make the function external!");
160}
161
162/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
163/// module, split the functions OUT of the specified module, and place them in
164/// the new module.
165///
166/// FIXME: this could be made DRAMATICALLY more efficient for large programs if
167/// we just MOVED functions from one module to the other, instead of cloning the
168/// whole module, then proceeding to delete an entire module's worth of stuff.
169///
170Module *llvm::SplitFunctionsOutOfModule(Module *M,
171                                        const std::vector<Function*> &F) {
172  // Make sure functions & globals are all external so that linkage
173  // between the two modules will work.
174  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
175    I->setLinkage(GlobalValue::ExternalLinkage);
176  for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
177    I->setLinkage(GlobalValue::ExternalLinkage);
178
179  Module *New = CloneModule(M);
180
181  // Make sure global initializers exist only in the safe module (CBE->.so)
182  for (Module::giterator I = New->gbegin(), E = New->gend(); I != E; ++I)
183    I->setInitializer(0);  // Delete the initializer to make it external
184
185  // Remove the Test functions from the Safe module
186  for (unsigned i = 0, e = F.size(); i != e; ++i) {
187    Function *TNOF = M->getFunction(F[i]->getName(), F[i]->getFunctionType());
188    DEBUG(std::cerr << "Removing function " << F[i]->getName() << "\n");
189    assert(TNOF && "Function doesn't exist in module!");
190    DeleteFunctionBody(TNOF);       // Function is now external in this module!
191  }
192
193  // Remove the Safe functions from the Test module
194  for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I) {
195    bool funcFound = false;
196    for (std::vector<Function*>::const_iterator FI = F.begin(), Fe = F.end();
197         FI != Fe; ++FI)
198      if (I->getName() == (*FI)->getName()) funcFound = true;
199
200    if (!funcFound)
201      DeleteFunctionBody(I);
202  }
203  return New;
204}
205