Move ToolRunner.(cpp|h) into the bugpoint directory
[oota-llvm.git] / tools / bugpoint / CrashDebugger.cpp
1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
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 defines the bugpoint internals that narrow down compilation crashes
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "BugDriver.h"
15 #include "ToolRunner.h"
16 #include "ListReducer.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/Pass.h"
21 #include "llvm/PassManager.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Type.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Bytecode/Writer.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/CommandLine.h"
31 #include <fstream>
32 #include <set>
33 using namespace llvm;
34
35 namespace {
36   cl::opt<bool>
37   KeepMain("keep-main",
38            cl::desc("Force function reduction to keep main"),
39            cl::init(false));
40 }
41
42 namespace llvm {
43   class ReducePassList : public ListReducer<const PassInfo*> {
44     BugDriver &BD;
45   public:
46     ReducePassList(BugDriver &bd) : BD(bd) {}
47
48     // doTest - Return true iff running the "removed" passes succeeds, and
49     // running the "Kept" passes fail when run on the output of the "removed"
50     // passes.  If we return true, we update the current module of bugpoint.
51     //
52     virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
53                               std::vector<const PassInfo*> &Kept);
54   };
55 }
56
57 ReducePassList::TestResult
58 ReducePassList::doTest(std::vector<const PassInfo*> &Prefix,
59                        std::vector<const PassInfo*> &Suffix) {
60   sys::Path PrefixOutput;
61   Module *OrigProgram = 0;
62   if (!Prefix.empty()) {
63     std::cout << "Checking to see if these passes crash: "
64               << getPassesString(Prefix) << ": ";
65     std::string PfxOutput;
66     if (BD.runPasses(Prefix, PfxOutput))
67       return KeepPrefix;
68
69     PrefixOutput.set(PfxOutput);
70     OrigProgram = BD.Program;
71
72     BD.Program = ParseInputFile(PrefixOutput.toString());
73     if (BD.Program == 0) {
74       std::cerr << BD.getToolName() << ": Error reading bytecode file '"
75                 << PrefixOutput << "'!\n";
76       exit(1);
77     }
78     PrefixOutput.eraseFromDisk();
79   }
80
81   std::cout << "Checking to see if these passes crash: "
82             << getPassesString(Suffix) << ": ";
83
84   if (BD.runPasses(Suffix)) {
85     delete OrigProgram;            // The suffix crashes alone...
86     return KeepSuffix;
87   }
88
89   // Nothing failed, restore state...
90   if (OrigProgram) {
91     delete BD.Program;
92     BD.Program = OrigProgram;
93   }
94   return NoFailure;
95 }
96
97 namespace llvm {
98   class ReduceCrashingFunctions : public ListReducer<Function*> {
99     BugDriver &BD;
100     bool (*TestFn)(BugDriver &, Module *);
101   public:
102     ReduceCrashingFunctions(BugDriver &bd,
103                             bool (*testFn)(BugDriver &, Module *))
104       : BD(bd), TestFn(testFn) {}
105
106     virtual TestResult doTest(std::vector<Function*> &Prefix,
107                               std::vector<Function*> &Kept) {
108       if (!Kept.empty() && TestFuncs(Kept))
109         return KeepSuffix;
110       if (!Prefix.empty() && TestFuncs(Prefix))
111         return KeepPrefix;
112       return NoFailure;
113     }
114
115     bool TestFuncs(std::vector<Function*> &Prefix);
116   };
117 }
118
119 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
120
121   //if main isn't present, claim there is no problem
122   if (KeepMain && find(Funcs.begin(), Funcs.end(), BD.getProgram()->getMainFunction()) == Funcs.end())
123     return false;
124
125   // Clone the program to try hacking it apart...
126   Module *M = CloneModule(BD.getProgram());
127
128   // Convert list to set for fast lookup...
129   std::set<Function*> Functions;
130   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
131     // FIXME: bugpoint should add names to all stripped symbols.
132     assert(!Funcs[i]->getName().empty() &&
133            "Bugpoint doesn't work on stripped modules yet PR718!");
134     Function *CMF = M->getFunction(Funcs[i]->getName(),
135                                    Funcs[i]->getFunctionType());
136     assert(CMF && "Function not in module?!");
137     Functions.insert(CMF);
138   }
139
140   std::cout << "Checking for crash with only these functions: ";
141   PrintFunctionList(Funcs);
142   std::cout << ": ";
143
144   // Loop over and delete any functions which we aren't supposed to be playing
145   // with...
146   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
147     if (!I->isExternal() && !Functions.count(I))
148       DeleteFunctionBody(I);
149
150   // Try running the hacked up program...
151   if (TestFn(BD, M)) {
152     BD.setNewProgram(M);        // It crashed, keep the trimmed version...
153
154     // Make sure to use function pointers that point into the now-current
155     // module.
156     Funcs.assign(Functions.begin(), Functions.end());
157     return true;
158   }
159   delete M;
160   return false;
161 }
162
163
164 namespace {
165   /// ReduceCrashingBlocks reducer - This works by setting the terminators of
166   /// all terminators except the specified basic blocks to a 'ret' instruction,
167   /// then running the simplify-cfg pass.  This has the effect of chopping up
168   /// the CFG really fast which can reduce large functions quickly.
169   ///
170   class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
171     BugDriver &BD;
172     bool (*TestFn)(BugDriver &, Module *);
173   public:
174     ReduceCrashingBlocks(BugDriver &bd, bool (*testFn)(BugDriver &, Module *))
175       : BD(bd), TestFn(testFn) {}
176
177     virtual TestResult doTest(std::vector<const BasicBlock*> &Prefix,
178                               std::vector<const BasicBlock*> &Kept) {
179       if (!Kept.empty() && TestBlocks(Kept))
180         return KeepSuffix;
181       if (!Prefix.empty() && TestBlocks(Prefix))
182         return KeepPrefix;
183       return NoFailure;
184     }
185
186     bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
187   };
188 }
189
190 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
191   // Clone the program to try hacking it apart...
192   Module *M = CloneModule(BD.getProgram());
193
194   // Convert list to set for fast lookup...
195   std::set<BasicBlock*> Blocks;
196   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
197     // Convert the basic block from the original module to the new module...
198     const Function *F = BBs[i]->getParent();
199     Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
200     assert(CMF && "Function not in module?!");
201
202     // Get the mapped basic block...
203     Function::iterator CBI = CMF->begin();
204     std::advance(CBI, std::distance(F->begin(),
205                                     Function::const_iterator(BBs[i])));
206     Blocks.insert(CBI);
207   }
208
209   std::cout << "Checking for crash with only these blocks:";
210   unsigned NumPrint = Blocks.size();
211   if (NumPrint > 10) NumPrint = 10;
212   for (unsigned i = 0, e = NumPrint; i != e; ++i)
213     std::cout << " " << BBs[i]->getName();
214   if (NumPrint < Blocks.size())
215     std::cout << "... <" << Blocks.size() << " total>";
216   std::cout << ": ";
217
218   // Loop over and delete any hack up any blocks that are not listed...
219   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
220     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
221       if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
222         // Loop over all of the successors of this block, deleting any PHI nodes
223         // that might include it.
224         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
225           (*SI)->removePredecessor(BB);
226
227         if (BB->getTerminator()->getType() != Type::VoidTy)
228           BB->getTerminator()->replaceAllUsesWith(
229                       Constant::getNullValue(BB->getTerminator()->getType()));
230
231         // Delete the old terminator instruction...
232         BB->getInstList().pop_back();
233
234         // Add a new return instruction of the appropriate type...
235         const Type *RetTy = BB->getParent()->getReturnType();
236         new ReturnInst(RetTy == Type::VoidTy ? 0 :
237                        Constant::getNullValue(RetTy), BB);
238       }
239
240   // The CFG Simplifier pass may delete one of the basic blocks we are
241   // interested in.  If it does we need to take the block out of the list.  Make
242   // a "persistent mapping" by turning basic blocks into <function, name> pairs.
243   // This won't work well if blocks are unnamed, but that is just the risk we
244   // have to take.
245   std::vector<std::pair<Function*, std::string> > BlockInfo;
246
247   for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
248        I != E; ++I)
249     BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
250
251   // Now run the CFG simplify pass on the function...
252   PassManager Passes;
253   Passes.add(createCFGSimplificationPass());
254   Passes.add(createVerifierPass());
255   Passes.run(*M);
256
257   // Try running on the hacked up program...
258   if (TestFn(BD, M)) {
259     BD.setNewProgram(M);      // It crashed, keep the trimmed version...
260
261     // Make sure to use basic block pointers that point into the now-current
262     // module, and that they don't include any deleted blocks.
263     BBs.clear();
264     for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
265       SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
266       SymbolTable::plane_iterator PI = ST.find(Type::LabelTy);
267       if (PI != ST.plane_end() && PI->second.count(BlockInfo[i].second))
268         BBs.push_back(cast<BasicBlock>(PI->second[BlockInfo[i].second]));
269     }
270     return true;
271   }
272   delete M;  // It didn't crash, try something else.
273   return false;
274 }
275
276 /// DebugACrash - Given a predicate that determines whether a component crashes
277 /// on a program, try to destructively reduce the program while still keeping
278 /// the predicate true.
279 static bool DebugACrash(BugDriver &BD,  bool (*TestFn)(BugDriver &, Module *)) {
280   // See if we can get away with nuking all of the global variable initializers
281   // in the program...
282   if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
283     Module *M = CloneModule(BD.getProgram());
284     bool DeletedInit = false;
285     for (Module::global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
286       if (I->hasInitializer()) {
287         I->setInitializer(0);
288         I->setLinkage(GlobalValue::ExternalLinkage);
289         DeletedInit = true;
290       }
291
292     if (!DeletedInit) {
293       delete M;  // No change made...
294     } else {
295       // See if the program still causes a crash...
296       std::cout << "\nChecking to see if we can delete global inits: ";
297       if (TestFn(BD, M)) {  // Still crashes?
298         BD.setNewProgram(M);
299         std::cout << "\n*** Able to remove all global initializers!\n";
300       } else {                       // No longer crashes?
301         std::cout << "  - Removing all global inits hides problem!\n";
302         delete M;
303       }
304     }
305   }
306
307   // Now try to reduce the number of functions in the module to something small.
308   std::vector<Function*> Functions;
309   for (Module::iterator I = BD.getProgram()->begin(),
310          E = BD.getProgram()->end(); I != E; ++I)
311     if (!I->isExternal())
312       Functions.push_back(I);
313
314   if (Functions.size() > 1 && !BugpointIsInterrupted) {
315     std::cout << "\n*** Attempting to reduce the number of functions "
316       "in the testcase\n";
317
318     unsigned OldSize = Functions.size();
319     ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
320
321     if (Functions.size() < OldSize)
322       BD.EmitProgressBytecode("reduced-function");
323   }
324
325   // Attempt to delete entire basic blocks at a time to speed up
326   // convergence... this actually works by setting the terminator of the blocks
327   // to a return instruction then running simplifycfg, which can potentially
328   // shrinks the code dramatically quickly
329   //
330   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
331     std::vector<const BasicBlock*> Blocks;
332     for (Module::const_iterator I = BD.getProgram()->begin(),
333            E = BD.getProgram()->end(); I != E; ++I)
334       for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
335         Blocks.push_back(FI);
336     ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
337   }
338
339   // FIXME: This should use the list reducer to converge faster by deleting
340   // larger chunks of instructions at a time!
341   unsigned Simplification = 2;
342   do {
343     if (BugpointIsInterrupted) break;
344     --Simplification;
345     std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
346               << "tions: Simplification Level #" << Simplification << '\n';
347
348     // Now that we have deleted the functions that are unnecessary for the
349     // program, try to remove instructions that are not necessary to cause the
350     // crash.  To do this, we loop through all of the instructions in the
351     // remaining functions, deleting them (replacing any values produced with
352     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
353     // still triggers failure, keep deleting until we cannot trigger failure
354     // anymore.
355     //
356     unsigned InstructionsToSkipBeforeDeleting = 0;
357   TryAgain:
358
359     // Loop over all of the (non-terminator) instructions remaining in the
360     // function, attempting to delete them.
361     unsigned CurInstructionNum = 0;
362     for (Module::const_iterator FI = BD.getProgram()->begin(),
363            E = BD.getProgram()->end(); FI != E; ++FI)
364       if (!FI->isExternal())
365         for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
366              ++BI)
367           for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
368                I != E; ++I, ++CurInstructionNum)
369             if (InstructionsToSkipBeforeDeleting) {
370               --InstructionsToSkipBeforeDeleting;
371             } else {
372               if (BugpointIsInterrupted) goto ExitLoops;
373
374               std::cout << "Checking instruction '" << I->getName() << "': ";
375               Module *M = BD.deleteInstructionFromProgram(I, Simplification);
376
377               // Find out if the pass still crashes on this pass...
378               if (TestFn(BD, M)) {
379                 // Yup, it does, we delete the old module, and continue trying
380                 // to reduce the testcase...
381                 BD.setNewProgram(M);
382                 InstructionsToSkipBeforeDeleting = CurInstructionNum;
383                 goto TryAgain;  // I wish I had a multi-level break here!
384               }
385
386               // This pass didn't crash without this instruction, try the next
387               // one.
388               delete M;
389             }
390
391     if (InstructionsToSkipBeforeDeleting) {
392       InstructionsToSkipBeforeDeleting = 0;
393       goto TryAgain;
394     }
395
396   } while (Simplification);
397 ExitLoops:
398
399   // Try to clean up the testcase by running funcresolve and globaldce...
400   if (!BugpointIsInterrupted) {
401     std::cout << "\n*** Attempting to perform final cleanups: ";
402     Module *M = CloneModule(BD.getProgram());
403     M = BD.performFinalCleanups(M, true);
404
405     // Find out if the pass still crashes on the cleaned up program...
406     if (TestFn(BD, M)) {
407       BD.setNewProgram(M);     // Yup, it does, keep the reduced version...
408     } else {
409       delete M;
410     }
411   }
412
413   BD.EmitProgressBytecode("reduced-simplified");
414
415   return false;
416 }
417
418 static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
419   return BD.runPasses(M);
420 }
421
422 /// debugOptimizerCrash - This method is called when some pass crashes on input.
423 /// It attempts to prune down the testcase to something reasonable, and figure
424 /// out exactly which pass is crashing.
425 ///
426 bool BugDriver::debugOptimizerCrash() {
427   std::cout << "\n*** Debugging optimizer crash!\n";
428
429   // Reduce the list of passes which causes the optimizer to crash...
430   unsigned OldSize = PassesToRun.size();
431   if (!BugpointIsInterrupted)
432     ReducePassList(*this).reduceList(PassesToRun);
433
434   std::cout << "\n*** Found crashing pass"
435             << (PassesToRun.size() == 1 ? ": " : "es: ")
436             << getPassesString(PassesToRun) << '\n';
437
438   EmitProgressBytecode("passinput");
439
440   return DebugACrash(*this, TestForOptimizerCrash);
441 }
442
443 static bool TestForCodeGenCrash(BugDriver &BD, Module *M) {
444   try {
445     std::cerr << '\n';
446     BD.compileProgram(M);
447     std::cerr << '\n';
448     return false;
449   } catch (ToolExecutionError &) {
450     std::cerr << "<crash>\n";
451     return true;  // Tool is still crashing.
452   }
453 }
454
455 /// debugCodeGeneratorCrash - This method is called when the code generator
456 /// crashes on an input.  It attempts to reduce the input as much as possible
457 /// while still causing the code generator to crash.
458 bool BugDriver::debugCodeGeneratorCrash() {
459   std::cerr << "*** Debugging code generator crash!\n";
460
461   return DebugACrash(*this, TestForCodeGenCrash);
462 }