1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines the bugpoint internals that narrow down compilation crashes
12 //===----------------------------------------------------------------------===//
14 #include "BugDriver.h"
15 #include "ListReducer.h"
16 #include "llvm/Constant.h"
17 #include "llvm/iTerminators.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"
35 class ReducePassList : public ListReducer<const PassInfo*> {
38 ReducePassList(BugDriver &bd) : BD(bd) {}
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.
44 virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
45 std::vector<const PassInfo*> &Kept);
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))
60 OrigProgram = BD.Program;
62 BD.Program = BD.ParseInputFile(PrefixOutput);
63 if (BD.Program == 0) {
64 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
65 << PrefixOutput << "'!\n";
68 removeFile(PrefixOutput);
71 std::cout << "Checking to see if these passes crash: "
72 << getPassesString(Suffix) << ": ";
74 if (BD.runPasses(Suffix)) {
75 delete OrigProgram; // The suffix crashes alone...
79 // Nothing failed, restore state...
82 BD.Program = OrigProgram;
88 class ReduceCrashingFunctions : public ListReducer<const Function*> {
90 bool (*TestFn)(BugDriver &, Module *);
92 ReduceCrashingFunctions(BugDriver &bd,
93 bool (*testFn)(BugDriver &, Module *))
94 : BD(bd), TestFn(testFn) {}
96 virtual TestResult doTest(std::vector<const Function*> &Prefix,
97 std::vector<const Function*> &Kept) {
98 if (!Kept.empty() && TestFuncs(Kept))
100 if (!Prefix.empty() && TestFuncs(Prefix))
105 bool TestFuncs(std::vector<const Function*> &Prefix);
109 bool ReduceCrashingFunctions::TestFuncs(std::vector<const Function*> &Funcs) {
110 // Clone the program to try hacking it apart...
111 Module *M = CloneModule(BD.getProgram());
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);
122 std::cout << "Checking for crash with only these functions:";
123 unsigned NumPrint = Funcs.size();
124 if (NumPrint > 10) NumPrint = 10;
125 for (unsigned i = 0; i != NumPrint; ++i)
126 std::cout << " " << Funcs[i]->getName();
127 if (NumPrint < Funcs.size())
128 std::cout << "... <" << Funcs.size() << " total>";
131 // Loop over and delete any functions which we aren't supposed to be playing
133 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
134 if (!I->isExternal() && !Functions.count(I))
135 DeleteFunctionBody(I);
137 // Try running the hacked up program...
139 BD.setNewProgram(M); // It crashed, keep the trimmed version...
141 // Make sure to use function pointers that point into the now-current
143 Funcs.assign(Functions.begin(), Functions.end());
152 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
153 /// all terminators except the specified basic blocks to a 'ret' instruction,
154 /// then running the simplify-cfg pass. This has the effect of chopping up
155 /// the CFG really fast which can reduce large functions quickly.
157 class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
159 bool (*TestFn)(BugDriver &, Module *);
161 ReduceCrashingBlocks(BugDriver &bd, bool (*testFn)(BugDriver &, Module *))
162 : BD(bd), TestFn(testFn) {}
164 virtual TestResult doTest(std::vector<const BasicBlock*> &Prefix,
165 std::vector<const BasicBlock*> &Kept) {
166 if (!Kept.empty() && TestBlocks(Kept))
168 if (!Prefix.empty() && TestBlocks(Prefix))
173 bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
177 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
178 // Clone the program to try hacking it apart...
179 Module *M = CloneModule(BD.getProgram());
181 // Convert list to set for fast lookup...
182 std::set<BasicBlock*> Blocks;
183 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
184 // Convert the basic block from the original module to the new module...
185 const Function *F = BBs[i]->getParent();
186 Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
187 assert(CMF && "Function not in module?!");
189 // Get the mapped basic block...
190 Function::iterator CBI = CMF->begin();
191 std::advance(CBI, std::distance(F->begin(),
192 Function::const_iterator(BBs[i])));
196 std::cout << "Checking for crash with only these blocks:";
197 unsigned NumPrint = Blocks.size();
198 if (NumPrint > 10) NumPrint = 10;
199 for (unsigned i = 0, e = NumPrint; i != e; ++i)
200 std::cout << " " << BBs[i]->getName();
201 if (NumPrint < Blocks.size())
202 std::cout << "... <" << Blocks.size() << " total>";
205 // Loop over and delete any hack up any blocks that are not listed...
206 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
207 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
208 if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
209 // Loop over all of the successors of this block, deleting any PHI nodes
210 // that might include it.
211 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
212 (*SI)->removePredecessor(BB);
214 if (BB->getTerminator()->getType() != Type::VoidTy)
215 BB->getTerminator()->replaceAllUsesWith(
216 Constant::getNullValue(BB->getTerminator()->getType()));
218 // Delete the old terminator instruction...
219 BB->getInstList().pop_back();
221 // Add a new return instruction of the appropriate type...
222 const Type *RetTy = BB->getParent()->getReturnType();
223 new ReturnInst(RetTy == Type::VoidTy ? 0 :
224 Constant::getNullValue(RetTy), BB);
227 // The CFG Simplifier pass may delete one of the basic blocks we are
228 // interested in. If it does we need to take the block out of the list. Make
229 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
230 // This won't work well if blocks are unnamed, but that is just the risk we
232 std::vector<std::pair<Function*, std::string> > BlockInfo;
234 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
236 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
238 // Now run the CFG simplify pass on the function...
240 Passes.add(createCFGSimplificationPass());
241 Passes.add(createVerifierPass());
244 // Try running on the hacked up program...
246 BD.setNewProgram(M); // It crashed, keep the trimmed version...
248 // Make sure to use basic block pointers that point into the now-current
249 // module, and that they don't include any deleted blocks.
251 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
252 SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
253 SymbolTable::iterator I = ST.find(Type::LabelTy);
254 if (I != ST.end() && I->second.count(BlockInfo[i].second))
255 BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
259 delete M; // It didn't crash, try something else.
263 /// DebugACrash - Given a predicate that determines whether a component crashes
264 /// on a program, try to destructively reduce the program while still keeping
265 /// the predicate true.
266 static bool DebugACrash(BugDriver &BD, bool (*TestFn)(BugDriver &, Module *)) {
267 bool AnyReduction = false;
269 // See if we can get away with nuking all of the global variable initializers
271 if (BD.getProgram()->gbegin() != BD.getProgram()->gend()) {
272 Module *M = CloneModule(BD.getProgram());
273 bool DeletedInit = false;
274 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
275 if (I->hasInitializer()) {
276 I->setInitializer(0);
277 I->setLinkage(GlobalValue::ExternalLinkage);
282 delete M; // No change made...
284 // See if the program still causes a crash...
285 std::cout << "\nChecking to see if we can delete global inits: ";
286 if (TestFn(BD, M)) { // Still crashes?
289 std::cout << "\n*** Able to remove all global initializers!\n";
290 } else { // No longer crashes?
291 std::cout << " - Removing all global inits hides problem!\n";
297 // Now try to reduce the number of functions in the module to something small.
298 std::vector<const Function*> Functions;
299 for (Module::const_iterator I = BD.getProgram()->begin(),
300 E = BD.getProgram()->end(); I != E; ++I)
301 if (!I->isExternal())
302 Functions.push_back(I);
304 if (Functions.size() > 1) {
305 std::cout << "\n*** Attempting to reduce the number of functions "
308 unsigned OldSize = Functions.size();
309 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
311 if (Functions.size() < OldSize) {
312 BD.EmitProgressBytecode("reduced-function");
317 // Attempt to delete entire basic blocks at a time to speed up
318 // convergence... this actually works by setting the terminator of the blocks
319 // to a return instruction then running simplifycfg, which can potentially
320 // shrinks the code dramatically quickly
322 if (!DisableSimplifyCFG) {
323 std::vector<const BasicBlock*> Blocks;
324 for (Module::const_iterator I = BD.getProgram()->begin(),
325 E = BD.getProgram()->end(); I != E; ++I)
326 for (Function::const_iterator FI = I->begin(), E = I->end(); FI !=E; ++FI)
327 Blocks.push_back(FI);
328 ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
331 // FIXME: This should use the list reducer to converge faster by deleting
332 // larger chunks of instructions at a time!
333 unsigned Simplification = 4;
336 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
337 << "tions: Simplification Level #" << Simplification << "\n";
339 // Now that we have deleted the functions that are unnecessary for the
340 // program, try to remove instructions that are not necessary to cause the
341 // crash. To do this, we loop through all of the instructions in the
342 // remaining functions, deleting them (replacing any values produced with
343 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
344 // still triggers failure, keep deleting until we cannot trigger failure
347 unsigned InstructionsToSkipBeforeDeleting = 0;
350 // Loop over all of the (non-terminator) instructions remaining in the
351 // function, attempting to delete them.
352 unsigned CurInstructionNum = 0;
353 for (Module::const_iterator FI = BD.getProgram()->begin(),
354 E = BD.getProgram()->end(); FI != E; ++FI)
355 if (!FI->isExternal())
356 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
358 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
359 I != E; ++I, ++CurInstructionNum)
360 if (InstructionsToSkipBeforeDeleting) {
361 --InstructionsToSkipBeforeDeleting;
363 std::cout << "Checking instruction '" << I->getName() << "': ";
364 Module *M = BD.deleteInstructionFromProgram(I, Simplification);
366 // Find out if the pass still crashes on this pass...
368 // Yup, it does, we delete the old module, and continue trying
369 // to reduce the testcase...
372 InstructionsToSkipBeforeDeleting = CurInstructionNum;
373 goto TryAgain; // I wish I had a multi-level break here!
376 // This pass didn't crash without this instruction, try the next
381 if (InstructionsToSkipBeforeDeleting) {
382 InstructionsToSkipBeforeDeleting = 0;
386 } while (Simplification);
388 // Try to clean up the testcase by running funcresolve and globaldce...
389 std::cout << "\n*** Attempting to perform final cleanups: ";
390 Module *M = CloneModule(BD.getProgram());
391 M = BD.performFinalCleanups(M, true);
393 // Find out if the pass still crashes on the cleaned up program...
395 BD.setNewProgram(M); // Yup, it does, keep the reduced version...
402 BD.EmitProgressBytecode("reduced-simplified");
407 static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
408 return BD.runPasses(M);
411 /// debugOptimizerCrash - This method is called when some pass crashes on input.
412 /// It attempts to prune down the testcase to something reasonable, and figure
413 /// out exactly which pass is crashing.
415 bool BugDriver::debugOptimizerCrash() {
416 std::cout << "\n*** Debugging optimizer crash!\n";
418 // Reduce the list of passes which causes the optimizer to crash...
419 unsigned OldSize = PassesToRun.size();
420 ReducePassList(*this).reduceList(PassesToRun);
422 std::cout << "\n*** Found crashing pass"
423 << (PassesToRun.size() == 1 ? ": " : "es: ")
424 << getPassesString(PassesToRun) << "\n";
426 EmitProgressBytecode("passinput");
428 return DebugACrash(*this, TestForOptimizerCrash);
431 static bool TestForCodeGenCrash(BugDriver &BD, Module *M) {
434 BD.compileProgram(M);
436 } catch (ToolExecutionError &TEE) {
437 std::cerr << "<crash>\n";
438 return true; // Tool is still crashing.
442 /// debugCodeGeneratorCrash - This method is called when the code generator
443 /// crashes on an input. It attempts to reduce the input as much as possible
444 /// while still causing the code generator to crash.
445 bool BugDriver::debugCodeGeneratorCrash() {
446 std::cerr << "*** Debugging code generator crash!\n";
448 return DebugACrash(*this, TestForCodeGenCrash);