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