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