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/Transforms/Scalar.h"
27 #include "llvm/Transforms/Utils/Cloning.h"
28 #include "Support/FileUtilities.h"
34 class ReducePassList : public ListReducer<const PassInfo*> {
37 ReducePassList(BugDriver &bd) : BD(bd) {}
39 // doTest - Return true iff running the "removed" passes succeeds, and
40 // running the "Kept" passes fail when run on the output of the "removed"
41 // passes. If we return true, we update the current module of bugpoint.
43 virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
44 std::vector<const PassInfo*> &Kept);
48 ReducePassList::TestResult
49 ReducePassList::doTest(std::vector<const PassInfo*> &Prefix,
50 std::vector<const PassInfo*> &Suffix) {
51 std::string PrefixOutput;
52 Module *OrigProgram = 0;
53 if (!Prefix.empty()) {
54 std::cout << "Checking to see if these passes crash: "
55 << getPassesString(Prefix) << ": ";
56 if (BD.runPasses(Prefix, PrefixOutput))
59 OrigProgram = BD.Program;
61 BD.Program = BD.ParseInputFile(PrefixOutput);
62 if (BD.Program == 0) {
63 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
64 << PrefixOutput << "'!\n";
67 removeFile(PrefixOutput);
70 std::cout << "Checking to see if these passes crash: "
71 << getPassesString(Suffix) << ": ";
73 if (BD.runPasses(Suffix)) {
74 delete OrigProgram; // The suffix crashes alone...
78 // Nothing failed, restore state...
81 BD.Program = OrigProgram;
87 class ReduceCrashingFunctions : public ListReducer<Function*> {
90 ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
92 virtual TestResult doTest(std::vector<Function*> &Prefix,
93 std::vector<Function*> &Kept) {
94 if (!Kept.empty() && TestFuncs(Kept))
96 if (!Prefix.empty() && TestFuncs(Prefix))
101 bool TestFuncs(std::vector<Function*> &Prefix);
105 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
106 // Clone the program to try hacking it apart...
107 Module *M = CloneModule(BD.getProgram());
109 // Convert list to set for fast lookup...
110 std::set<Function*> Functions;
111 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
112 Function *CMF = M->getFunction(Funcs[i]->getName(),
113 Funcs[i]->getFunctionType());
114 assert(CMF && "Function not in module?!");
115 Functions.insert(CMF);
118 std::cout << "Checking for crash with only these functions:";
119 unsigned NumPrint = Funcs.size();
120 if (NumPrint > 10) NumPrint = 10;
121 for (unsigned i = 0; i != NumPrint; ++i)
122 std::cout << " " << Funcs[i]->getName();
123 if (NumPrint < Funcs.size())
124 std::cout << "... <" << Funcs.size() << " total>";
127 // Loop over and delete any functions which we aren't supposed to be playing
129 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
130 if (!I->isExternal() && !Functions.count(I))
131 DeleteFunctionBody(I);
133 // Try running the hacked up program...
134 if (BD.runPasses(M)) {
135 BD.setNewProgram(M); // It crashed, keep the trimmed version...
137 // Make sure to use function pointers that point into the now-current
139 Funcs.assign(Functions.begin(), Functions.end());
148 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
149 /// all terminators except the specified basic blocks to a 'ret' instruction,
150 /// then running the simplify-cfg pass. This has the effect of chopping up
151 /// the CFG really fast which can reduce large functions quickly.
153 class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
156 ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
158 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
159 std::vector<BasicBlock*> &Kept) {
160 if (!Kept.empty() && TestBlocks(Kept))
162 if (!Prefix.empty() && TestBlocks(Prefix))
167 bool TestBlocks(std::vector<BasicBlock*> &Prefix);
171 bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
172 // Clone the program to try hacking it apart...
173 Module *M = CloneModule(BD.getProgram());
175 // Convert list to set for fast lookup...
176 std::set<BasicBlock*> Blocks;
177 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
178 // Convert the basic block from the original module to the new module...
179 Function *F = BBs[i]->getParent();
180 Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
181 assert(CMF && "Function not in module?!");
183 // Get the mapped basic block...
184 Function::iterator CBI = CMF->begin();
185 std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
189 std::cout << "Checking for crash with only these blocks:";
190 unsigned NumPrint = Blocks.size();
191 if (NumPrint > 10) NumPrint = 10;
192 for (unsigned i = 0, e = NumPrint; i != e; ++i)
193 std::cout << " " << BBs[i]->getName();
194 if (NumPrint < Blocks.size())
195 std::cout << "... <" << Blocks.size() << " total>";
198 // Loop over and delete any hack up any blocks that are not listed...
199 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
200 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
201 if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
202 // Loop over all of the successors of this block, deleting any PHI nodes
203 // that might include it.
204 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
205 (*SI)->removePredecessor(BB);
207 if (BB->getTerminator()->getType() != Type::VoidTy)
208 BB->getTerminator()->replaceAllUsesWith(
209 Constant::getNullValue(BB->getTerminator()->getType()));
211 // Delete the old terminator instruction...
212 BB->getInstList().pop_back();
214 // Add a new return instruction of the appropriate type...
215 const Type *RetTy = BB->getParent()->getReturnType();
216 new ReturnInst(RetTy == Type::VoidTy ? 0 :
217 Constant::getNullValue(RetTy), BB);
220 // The CFG Simplifier pass may delete one of the basic blocks we are
221 // interested in. If it does we need to take the block out of the list. Make
222 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
223 // This won't work well if blocks are unnamed, but that is just the risk we
225 std::vector<std::pair<Function*, std::string> > BlockInfo;
227 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
229 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
231 // Now run the CFG simplify pass on the function...
233 Passes.add(createCFGSimplificationPass());
234 Passes.add(createVerifierPass());
237 // Try running on the hacked up program...
238 if (BD.runPasses(M)) {
239 BD.setNewProgram(M); // It crashed, keep the trimmed version...
241 // Make sure to use basic block pointers that point into the now-current
242 // module, and that they don't include any deleted blocks.
244 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
245 SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
246 SymbolTable::iterator I = ST.find(Type::LabelTy);
247 if (I != ST.end() && I->second.count(BlockInfo[i].second))
248 BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
252 delete M; // It didn't crash, try something else.
256 static bool TestForOptimizerCrash(BugDriver &BD) {
257 return BD.runPasses();
261 /// debugOptimizerCrash - This method is called when some pass crashes on input.
262 /// It attempts to prune down the testcase to something reasonable, and figure
263 /// out exactly which pass is crashing.
265 bool BugDriver::debugOptimizerCrash() {
266 bool AnyReduction = false;
267 std::cout << "\n*** Debugging optimizer crash!\n";
269 // Reduce the list of passes which causes the optimizer to crash...
270 unsigned OldSize = PassesToRun.size();
271 ReducePassList(*this).reduceList(PassesToRun);
273 std::cout << "\n*** Found crashing pass"
274 << (PassesToRun.size() == 1 ? ": " : "es: ")
275 << getPassesString(PassesToRun) << "\n";
277 EmitProgressBytecode("passinput");
279 // See if we can get away with nuking all of the global variable initializers
281 if (Program->gbegin() != Program->gend()) {
282 Module *M = CloneModule(Program);
283 bool DeletedInit = false;
284 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
285 if (I->hasInitializer()) {
286 I->setInitializer(0);
287 I->setLinkage(GlobalValue::ExternalLinkage);
292 delete M; // No change made...
294 // See if the program still causes a crash...
295 std::cout << "\nChecking to see if we can delete global inits: ";
296 if (runPasses(M)) { // Still crashes?
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";
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 = Program->begin(), E = Program->end(); I != E; ++I)
310 if (!I->isExternal())
311 Functions.push_back(I);
313 if (Functions.size() > 1) {
314 std::cout << "\n*** Attempting to reduce the number of functions "
317 OldSize = Functions.size();
318 ReduceCrashingFunctions(*this).reduceList(Functions);
320 if (Functions.size() < OldSize) {
321 EmitProgressBytecode("reduced-function");
326 // Attempt to delete entire basic blocks at a time to speed up
327 // convergence... this actually works by setting the terminator of the blocks
328 // to a return instruction then running simplifycfg, which can potentially
329 // shrinks the code dramatically quickly
331 if (!DisableSimplifyCFG) {
332 std::vector<BasicBlock*> Blocks;
333 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
334 for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
335 Blocks.push_back(FI);
336 ReduceCrashingBlocks(*this).reduceList(Blocks);
339 // FIXME: This should use the list reducer to converge faster by deleting
340 // larger chunks of instructions at a time!
341 unsigned Simplification = 4;
344 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
345 << "tions: Simplification Level #" << Simplification << "\n";
347 // Now that we have deleted the functions that are unnecessary for the
348 // program, try to remove instructions that are not necessary to cause the
349 // crash. To do this, we loop through all of the instructions in the
350 // remaining functions, deleting them (replacing any values produced with
351 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
352 // still triggers failure, keep deleting until we cannot trigger failure
357 // Loop over all of the (non-terminator) instructions remaining in the
358 // function, attempting to delete them.
359 for (Module::iterator FI = Program->begin(), E = Program->end();
361 if (!FI->isExternal()) {
362 for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
363 for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
365 Module *M = deleteInstructionFromProgram(I, Simplification);
367 // Find out if the pass still crashes on this pass...
368 std::cout << "Checking instruction '" << I->getName() << "': ";
370 // Yup, it does, we delete the old module, and continue trying to
371 // reduce the testcase...
374 goto TryAgain; // I wish I had a multi-level break here!
377 // This pass didn't crash without this instruction, try the next
382 } while (Simplification);
384 // Try to clean up the testcase by running funcresolve and globaldce...
385 std::cout << "\n*** Attempting to perform final cleanups: ";
386 Module *M = CloneModule(Program);
387 M = performFinalCleanups(M, true);
389 // Find out if the pass still crashes on the cleaned up program...
391 setNewProgram(M); // Yup, it does, keep the reduced version...
398 EmitProgressBytecode("reduced-simplified");
405 /// debugCodeGeneratorCrash - This method is called when the code generator
406 /// crashes on an input. It attempts to reduce the input as much as possible
407 /// while still causing the code generator to crash.
408 bool BugDriver::debugCodeGeneratorCrash() {
409 std::cerr << "*** Debugging code generator crash!\n";