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 DebugCrashes : public ListReducer<const PassInfo*> {
37 DebugCrashes(BugDriver &bd) : BD(bd) {}
39 // doTest - Return true iff running the "removed" passes succeeds, and running
40 // the "Kept" passes fail when run on the output of the "removed" passes. If
41 // 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);
47 DebugCrashes::TestResult
48 DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
49 std::vector<const PassInfo*> &Suffix) {
50 std::string PrefixOutput;
51 Module *OrigProgram = 0;
52 if (!Prefix.empty()) {
53 std::cout << "Checking to see if these passes crash: "
54 << getPassesString(Prefix) << ": ";
55 if (BD.runPasses(Prefix, PrefixOutput))
58 OrigProgram = BD.Program;
60 BD.Program = BD.ParseInputFile(PrefixOutput);
61 if (BD.Program == 0) {
62 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
63 << PrefixOutput << "'!\n";
66 removeFile(PrefixOutput);
69 std::cout << "Checking to see if these passes crash: "
70 << getPassesString(Suffix) << ": ";
72 if (BD.runPasses(Suffix)) {
73 delete OrigProgram; // The suffix crashes alone...
77 // Nothing failed, restore state...
80 BD.Program = OrigProgram;
85 class ReduceCrashingFunctions : public ListReducer<Function*> {
88 ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
90 virtual TestResult doTest(std::vector<Function*> &Prefix,
91 std::vector<Function*> &Kept) {
92 if (!Kept.empty() && TestFuncs(Kept))
94 if (!Prefix.empty() && TestFuncs(Prefix))
99 bool TestFuncs(std::vector<Function*> &Prefix);
102 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
103 // Clone the program to try hacking it apart...
104 Module *M = CloneModule(BD.Program);
106 // Convert list to set for fast lookup...
107 std::set<Function*> Functions;
108 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
109 Function *CMF = M->getFunction(Funcs[i]->getName(),
110 Funcs[i]->getFunctionType());
111 assert(CMF && "Function not in module?!");
112 Functions.insert(CMF);
115 std::cout << "Checking for crash with only these functions:";
116 unsigned NumPrint = Funcs.size();
117 if (NumPrint > 10) NumPrint = 10;
118 for (unsigned i = 0; i != NumPrint; ++i)
119 std::cout << " " << Funcs[i]->getName();
120 if (NumPrint < Funcs.size())
121 std::cout << "... <" << Funcs.size() << " total>";
124 // Loop over and delete any functions which we aren't supposed to be playing
126 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
127 if (!I->isExternal() && !Functions.count(I))
128 DeleteFunctionBody(I);
130 // Try running the hacked up program...
131 std::swap(BD.Program, M);
132 if (BD.runPasses(BD.PassesToRun)) {
133 delete M; // It crashed, keep the trimmed version...
135 // Make sure to use function pointers that point into the now-current
137 Funcs.assign(Functions.begin(), Functions.end());
140 delete BD.Program; // It didn't crash, revert...
146 /// ReduceCrashingBlocks reducer - This works by setting the terminators of all
147 /// terminators except the specified basic blocks to a 'ret' instruction, then
148 /// running the simplify-cfg pass. This has the effect of chopping up the CFG
149 /// really fast which can reduce large functions quickly.
151 class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
154 ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
156 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
157 std::vector<BasicBlock*> &Kept) {
158 if (!Kept.empty() && TestBlocks(Kept))
160 if (!Prefix.empty() && TestBlocks(Prefix))
165 bool TestBlocks(std::vector<BasicBlock*> &Prefix);
168 bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
169 // Clone the program to try hacking it apart...
170 Module *M = CloneModule(BD.Program);
172 // Convert list to set for fast lookup...
173 std::set<BasicBlock*> Blocks;
174 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
175 // Convert the basic block from the original module to the new module...
176 Function *F = BBs[i]->getParent();
177 Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
178 assert(CMF && "Function not in module?!");
180 // Get the mapped basic block...
181 Function::iterator CBI = CMF->begin();
182 std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
186 std::cout << "Checking for crash with only these blocks:";
187 unsigned NumPrint = Blocks.size();
188 if (NumPrint > 10) NumPrint = 10;
189 for (unsigned i = 0, e = NumPrint; i != e; ++i)
190 std::cout << " " << BBs[i]->getName();
191 if (NumPrint < Blocks.size())
192 std::cout << "... <" << Blocks.size() << " total>";
195 // Loop over and delete any hack up any blocks that are not listed...
196 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
197 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
198 if (!Blocks.count(BB) && BB->getTerminator()->getNumSuccessors()) {
199 // Loop over all of the successors of this block, deleting any PHI nodes
200 // that might include it.
201 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
202 (*SI)->removePredecessor(BB);
204 if (BB->getTerminator()->getType() != Type::VoidTy)
205 BB->getTerminator()->replaceAllUsesWith(
206 Constant::getNullValue(BB->getTerminator()->getType()));
208 // Delete the old terminator instruction...
209 BB->getInstList().pop_back();
211 // Add a new return instruction of the appropriate type...
212 const Type *RetTy = BB->getParent()->getReturnType();
213 new ReturnInst(RetTy == Type::VoidTy ? 0 :
214 Constant::getNullValue(RetTy), BB);
217 // The CFG Simplifier pass may delete one of the basic blocks we are
218 // interested in. If it does we need to take the block out of the list. Make
219 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
220 // This won't work well if blocks are unnamed, but that is just the risk we
222 std::vector<std::pair<Function*, std::string> > BlockInfo;
224 for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
226 BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
228 // Now run the CFG simplify pass on the function...
230 Passes.add(createCFGSimplificationPass());
231 Passes.add(createVerifierPass());
234 // Try running on the hacked up program...
235 std::swap(BD.Program, M);
236 if (BD.runPasses(BD.PassesToRun)) {
237 delete M; // It crashed, keep the trimmed version...
239 // Make sure to use basic block pointers that point into the now-current
240 // module, and that they don't include any deleted blocks.
242 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
243 SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
244 SymbolTable::iterator I = ST.find(Type::LabelTy);
245 if (I != ST.end() && I->second.count(BlockInfo[i].second))
246 BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
250 delete BD.Program; // It didn't crash, revert...
255 /// debugCrash - This method is called when some pass crashes on input. It
256 /// attempts to prune down the testcase to something reasonable, and figure
257 /// out exactly which pass is crashing.
259 bool BugDriver::debugCrash() {
260 bool AnyReduction = false;
261 std::cout << "\n*** Debugging optimizer crash!\n";
263 // Reduce the list of passes which causes the optimizer to crash...
264 unsigned OldSize = PassesToRun.size();
265 DebugCrashes(*this).reduceList(PassesToRun);
267 std::cout << "\n*** Found crashing pass"
268 << (PassesToRun.size() == 1 ? ": " : "es: ")
269 << getPassesString(PassesToRun) << "\n";
271 EmitProgressBytecode("passinput");
273 // See if we can get away with nuking all of the global variable initializers
275 if (Program->gbegin() != Program->gend()) {
276 Module *M = CloneModule(Program);
277 bool DeletedInit = false;
278 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
279 if (I->hasInitializer()) {
280 I->setInitializer(0);
281 I->setLinkage(GlobalValue::ExternalLinkage);
286 delete M; // No change made...
288 // See if the program still causes a crash...
289 std::cout << "\nChecking to see if we can delete global inits: ";
290 std::swap(Program, M);
291 if (runPasses(PassesToRun)) { // Still crashes?
294 std::cout << "\n*** Able to remove all global initializers!\n";
295 } else { // No longer crashes?
296 delete Program; // Restore program.
298 std::cout << " - Removing all global inits hides problem!\n";
303 // Now try to reduce the number of functions in the module to something small.
304 std::vector<Function*> Functions;
305 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
306 if (!I->isExternal())
307 Functions.push_back(I);
309 if (Functions.size() > 1) {
310 std::cout << "\n*** Attempting to reduce the number of functions "
313 OldSize = Functions.size();
314 ReduceCrashingFunctions(*this).reduceList(Functions);
316 if (Functions.size() < OldSize) {
317 EmitProgressBytecode("reduced-function");
322 // Attempt to delete entire basic blocks at a time to speed up
323 // convergence... this actually works by setting the terminator of the blocks
324 // to a return instruction then running simplifycfg, which can potentially
325 // shrinks the code dramatically quickly
327 if (!DisableSimplifyCFG) {
328 std::vector<BasicBlock*> Blocks;
329 for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
330 for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
331 Blocks.push_back(FI);
332 ReduceCrashingBlocks(*this).reduceList(Blocks);
335 // FIXME: This should use the list reducer to converge faster by deleting
336 // larger chunks of instructions at a time!
337 unsigned Simplification = 4;
340 std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
341 << "tions: Simplification Level #" << Simplification << "\n";
343 // Now that we have deleted the functions that are unnecessary for the
344 // program, try to remove instructions that are not necessary to cause the
345 // crash. To do this, we loop through all of the instructions in the
346 // remaining functions, deleting them (replacing any values produced with
347 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
348 // still triggers failure, keep deleting until we cannot trigger failure
353 // Loop over all of the (non-terminator) instructions remaining in the
354 // function, attempting to delete them.
355 for (Module::iterator FI = Program->begin(), E = Program->end();
357 if (!FI->isExternal()) {
358 for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
359 for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
361 Module *M = deleteInstructionFromProgram(I, Simplification);
363 // Make the function the current program...
364 std::swap(Program, M);
366 // Find out if the pass still crashes on this pass...
367 std::cout << "Checking instruction '" << I->getName() << "': ";
368 if (runPasses(PassesToRun)) {
369 // Yup, it does, we delete the old module, and continue trying to
370 // reduce the testcase...
373 goto TryAgain; // I wish I had a multi-level break here!
376 // 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);
388 std::swap(Program, M);
390 // Find out if the pass still crashes on the cleaned up program...
391 if (runPasses(PassesToRun)) {
392 // Yup, it does, keep the reduced version...
396 delete Program; // Otherwise, restore the original module...
401 EmitProgressBytecode("reduced-simplified");
406 } // End llvm namespace