Use errs() instead of std::cerr.
[oota-llvm.git] / tools / bugpoint / ExtractFunction.cpp
1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
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 // 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/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/Transforms/IPO.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/FunctionUtils.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/System/Path.h"
33 #include "llvm/System/Signals.h"
34 #include <set>
35 #include <fstream>
36 #include <iostream>
37 using namespace llvm;
38
39 namespace llvm {
40   bool DisableSimplifyCFG = false;
41 } // End llvm namespace
42
43 namespace {
44   cl::opt<bool>
45   NoDCE ("disable-dce",
46          cl::desc("Do not use the -dce pass to reduce testcases"));
47   cl::opt<bool, true>
48   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
49          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
50 }
51
52 /// deleteInstructionFromProgram - This method clones the current Program and
53 /// deletes the specified instruction from the cloned module.  It then runs a
54 /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
55 /// depends on the value.  The modified module is then returned.
56 ///
57 Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
58                                                 unsigned Simplification) const {
59   Module *Result = CloneModule(Program);
60
61   const BasicBlock *PBB = I->getParent();
62   const Function *PF = PBB->getParent();
63
64   Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
65   std::advance(RFI, std::distance(PF->getParent()->begin(),
66                                   Module::const_iterator(PF)));
67
68   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
69   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
70
71   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
72   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
73   Instruction *TheInst = RI;              // Got the corresponding instruction!
74
75   // If this instruction produces a value, replace any users with null values
76   if (isa<StructType>(TheInst->getType()))
77     TheInst->replaceAllUsesWith(Context.getUndef(TheInst->getType()));
78   else if (TheInst->getType() != Type::VoidTy)
79     TheInst->replaceAllUsesWith(Context.getNullValue(TheInst->getType()));
80
81   // Remove the instruction from the program.
82   TheInst->getParent()->getInstList().erase(TheInst);
83
84   
85   //writeProgramToFile("current.bc", Result);
86     
87   // Spiff up the output a little bit.
88   PassManager Passes;
89   // Make sure that the appropriate target data is always used...
90   Passes.add(new TargetData(Result));
91
92   /// FIXME: If this used runPasses() like the methods below, we could get rid
93   /// of the -disable-* options!
94   if (Simplification > 1 && !NoDCE)
95     Passes.add(createDeadCodeEliminationPass());
96   if (Simplification && !DisableSimplifyCFG)
97     Passes.add(createCFGSimplificationPass());      // Delete dead control flow
98
99   Passes.add(createVerifierPass());
100   Passes.run(*Result);
101   return Result;
102 }
103
104 static const PassInfo *getPI(Pass *P) {
105   const PassInfo *PI = P->getPassInfo();
106   delete P;
107   return PI;
108 }
109
110 /// performFinalCleanups - This method clones the current Program and performs
111 /// a series of cleanups intended to get rid of extra cruft on the module
112 /// before handing it to the user.
113 ///
114 Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
115   // Make all functions external, so GlobalDCE doesn't delete them...
116   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
117     I->setLinkage(GlobalValue::ExternalLinkage);
118
119   std::vector<const PassInfo*> CleanupPasses;
120   CleanupPasses.push_back(getPI(createGlobalDCEPass()));
121   CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
122
123   if (MayModifySemantics)
124     CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
125   else
126     CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
127
128   Module *New = runPassesOn(M, CleanupPasses);
129   if (New == 0) {
130     errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
131     return M;
132   }
133   delete M;
134   return New;
135 }
136
137
138 /// ExtractLoop - Given a module, extract up to one loop from it into a new
139 /// function.  This returns null if there are no extractable loops in the
140 /// program or if the loop extractor crashes.
141 Module *BugDriver::ExtractLoop(Module *M) {
142   std::vector<const PassInfo*> LoopExtractPasses;
143   LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
144
145   Module *NewM = runPassesOn(M, LoopExtractPasses);
146   if (NewM == 0) {
147     Module *Old = swapProgramIn(M);
148     std::cout << "*** Loop extraction failed: ";
149     EmitProgressBitcode("loopextraction", true);
150     std::cout << "*** Sorry. :(  Please report a bug!\n";
151     swapProgramIn(Old);
152     return 0;
153   }
154
155   // Check to see if we created any new functions.  If not, no loops were
156   // extracted and we should return null.  Limit the number of loops we extract
157   // to avoid taking forever.
158   static unsigned NumExtracted = 32;
159   if (M->size() == NewM->size() || --NumExtracted == 0) {
160     delete NewM;
161     return 0;
162   } else {
163     assert(M->size() < NewM->size() && "Loop extract removed functions?");
164     Module::iterator MI = NewM->begin();
165     for (unsigned i = 0, e = M->size(); i != e; ++i)
166       ++MI;
167   }
168
169   return NewM;
170 }
171
172
173 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
174 // blocks, making it external.
175 //
176 void llvm::DeleteFunctionBody(Function *F) {
177   // delete the body of the function...
178   F->deleteBody();
179   assert(F->isDeclaration() && "This didn't make the function external!");
180 }
181
182 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
183 /// as a constant array.
184 static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
185   assert(!TorList.empty() && "Don't create empty tor list!");
186   LLVMContext &Context = *TorList[0].first->getContext();
187   std::vector<Constant*> ArrayElts;
188   for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
189     std::vector<Constant*> Elts;
190     Elts.push_back(Context.getConstantInt(Type::Int32Ty, TorList[i].second));
191     Elts.push_back(TorList[i].first);
192     ArrayElts.push_back(Context.getConstantStruct(Elts));
193   }
194   return Context.getConstantArray(Context.getArrayType(ArrayElts[0]->getType(), 
195                                            ArrayElts.size()),
196                             ArrayElts);
197 }
198
199 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
200 /// M1 has all of the global variables.  If M2 contains any functions that are
201 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
202 /// prune appropriate entries out of M1s list.
203 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
204                                 DenseMap<const Value*, Value*> ValueMap) {
205   GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
206   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
207       !GV->use_empty()) return;
208   
209   std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
210   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
211   if (!InitList) return;
212   
213   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
214     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
215       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
216       
217       if (CS->getOperand(1)->isNullValue())
218         break;  // Found a null terminator, stop here.
219       
220       ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
221       int Priority = CI ? CI->getSExtValue() : 0;
222       
223       Constant *FP = CS->getOperand(1);
224       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
225         if (CE->isCast())
226           FP = CE->getOperand(0);
227       if (Function *F = dyn_cast<Function>(FP)) {
228         if (!F->isDeclaration())
229           M1Tors.push_back(std::make_pair(F, Priority));
230         else {
231           // Map to M2's version of the function.
232           F = cast<Function>(ValueMap[F]);
233           M2Tors.push_back(std::make_pair(F, Priority));
234         }
235       }
236     }
237   }
238   
239   GV->eraseFromParent();
240   if (!M1Tors.empty()) {
241     Constant *M1Init = GetTorInit(M1Tors);
242     new GlobalVariable(*M1, M1Init->getType(), false,
243                        GlobalValue::AppendingLinkage,
244                        M1Init, GlobalName);
245   }
246
247   GV = M2->getNamedGlobal(GlobalName);
248   assert(GV && "Not a clone of M1?");
249   assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
250
251   GV->eraseFromParent();
252   if (!M2Tors.empty()) {
253     Constant *M2Init = GetTorInit(M2Tors);
254     new GlobalVariable(*M2, M2Init->getType(), false,
255                        GlobalValue::AppendingLinkage,
256                        M2Init, GlobalName);
257   }
258 }
259
260
261 /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
262 /// module, split the functions OUT of the specified module, and place them in
263 /// the new module.
264 Module *
265 llvm::SplitFunctionsOutOfModule(Module *M,
266                                 const std::vector<Function*> &F,
267                                 DenseMap<const Value*, Value*> &ValueMap) {
268   // Make sure functions & globals are all external so that linkage
269   // between the two modules will work.
270   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
271     I->setLinkage(GlobalValue::ExternalLinkage);
272   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
273        I != E; ++I) {
274     if (I->hasName() && *I->getNameStart() == '\01')
275       I->setName(I->getNameStart()+1, I->getNameLen()-1);
276     I->setLinkage(GlobalValue::ExternalLinkage);
277   }
278
279   DenseMap<const Value*, Value*> NewValueMap;
280   Module *New = CloneModule(M, NewValueMap);
281
282   // Make sure global initializers exist only in the safe module (CBE->.so)
283   for (Module::global_iterator I = New->global_begin(), E = New->global_end();
284        I != E; ++I)
285     I->setInitializer(0);  // Delete the initializer to make it external
286
287   // Remove the Test functions from the Safe module
288   std::set<Function *> TestFunctions;
289   for (unsigned i = 0, e = F.size(); i != e; ++i) {
290     Function *TNOF = cast<Function>(ValueMap[F[i]]);
291     DEBUG(errs() << "Removing function ");
292     DEBUG(WriteAsOperand(errs(), TNOF, false));
293     DEBUG(errs() << "\n");
294     TestFunctions.insert(cast<Function>(NewValueMap[TNOF]));
295     DeleteFunctionBody(TNOF);       // Function is now external in this module!
296   }
297
298   
299   // Remove the Safe functions from the Test module
300   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
301     if (!TestFunctions.count(I))
302       DeleteFunctionBody(I);
303   
304
305   // Make sure that there is a global ctor/dtor array in both halves of the
306   // module if they both have static ctor/dtor functions.
307   SplitStaticCtorDtor("llvm.global_ctors", M, New, NewValueMap);
308   SplitStaticCtorDtor("llvm.global_dtors", M, New, NewValueMap);
309   
310   return New;
311 }
312
313 //===----------------------------------------------------------------------===//
314 // Basic Block Extraction Code
315 //===----------------------------------------------------------------------===//
316
317 /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
318 /// into their own functions.  The only detail is that M is actually a module
319 /// cloned from the one the BBs are in, so some mapping needs to be performed.
320 /// If this operation fails for some reason (ie the implementation is buggy),
321 /// this function should return null, otherwise it returns a new Module.
322 Module *BugDriver::ExtractMappedBlocksFromModule(const
323                                                  std::vector<BasicBlock*> &BBs,
324                                                  Module *M) {
325   char *ExtraArg = NULL;
326
327   sys::Path uniqueFilename("bugpoint-extractblocks");
328   std::string ErrMsg;
329   if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
330     std::cout << "*** Basic Block extraction failed!\n";
331     errs() << "Error creating temporary file: " << ErrMsg << "\n";
332     M = swapProgramIn(M);
333     EmitProgressBitcode("basicblockextractfail", true);
334     swapProgramIn(M);
335     return 0;
336   }
337   sys::RemoveFileOnSignal(uniqueFilename);
338
339   std::ofstream BlocksToNotExtractFile(uniqueFilename.c_str());
340   if (!BlocksToNotExtractFile) {
341     std::cout << "*** Basic Block extraction failed!\n";
342     errs() << "Error writing list of blocks to not extract: " << ErrMsg
343            << "\n";
344     M = swapProgramIn(M);
345     EmitProgressBitcode("basicblockextractfail", true);
346     swapProgramIn(M);
347     return 0;
348   }
349   for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
350        I != E; ++I) {
351     BasicBlock *BB = *I;
352     // If the BB doesn't have a name, give it one so we have something to key
353     // off of.
354     if (!BB->hasName()) BB->setName("tmpbb");
355     BlocksToNotExtractFile << BB->getParent()->getName() << " "
356                            << BB->getName() << "\n";
357   }
358   BlocksToNotExtractFile.close();
359
360   const char *uniqueFN = uniqueFilename.c_str();
361   ExtraArg = (char*)malloc(23 + strlen(uniqueFN));
362   strcat(strcpy(ExtraArg, "--extract-blocks-file="), uniqueFN);
363
364   std::vector<const PassInfo*> PI;
365   std::vector<BasicBlock *> EmptyBBs; // This parameter is ignored.
366   PI.push_back(getPI(createBlockExtractorPass(EmptyBBs)));
367   Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
368
369   if (uniqueFilename.exists())
370     uniqueFilename.eraseFromDisk(); // Free disk space
371   free(ExtraArg);
372
373   if (Ret == 0) {
374     std::cout << "*** Basic Block extraction failed, please report a bug!\n";
375     M = swapProgramIn(M);
376     EmitProgressBitcode("basicblockextractfail", true);
377     swapProgramIn(M);
378   }
379   return Ret;
380 }