1 //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "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"
38 cl::desc("Force function reduction to keep main"),
43 class ReducePassList
: public ListReducer
<const PassInfo
*> {
46 ReducePassList(BugDriver
&bd
) : BD(bd
) {}
48 // doTest - Return true iff running the "removed" passes succeeds, and
49 // running the "Kept" passes fail when run on the output of the "removed"
50 // passes. If we return true, we update the current module of bugpoint.
52 virtual TestResult
doTest(std::vector
<const PassInfo
*> &Removed
,
53 std::vector
<const PassInfo
*> &Kept
);
57 ReducePassList::TestResult
58 ReducePassList::doTest(std::vector
<const PassInfo
*> &Prefix
,
59 std::vector
<const PassInfo
*> &Suffix
) {
60 sys::Path PrefixOutput
;
61 Module
*OrigProgram
= 0;
62 if (!Prefix
.empty()) {
63 std::cout
<< "Checking to see if these passes crash: "
64 << getPassesString(Prefix
) << ": ";
65 std::string PfxOutput
;
66 if (BD
.runPasses(Prefix
, PfxOutput
))
69 PrefixOutput
.set(PfxOutput
);
70 OrigProgram
= BD
.Program
;
72 BD
.Program
= ParseInputFile(PrefixOutput
.toString());
73 if (BD
.Program
== 0) {
74 std::cerr
<< BD
.getToolName() << ": Error reading bitcode file '"
75 << PrefixOutput
<< "'!\n";
78 PrefixOutput
.eraseFromDisk();
81 std::cout
<< "Checking to see if these passes crash: "
82 << getPassesString(Suffix
) << ": ";
84 if (BD
.runPasses(Suffix
)) {
85 delete OrigProgram
; // The suffix crashes alone...
89 // Nothing failed, restore state...
92 BD
.Program
= OrigProgram
;
98 /// ReduceCrashingGlobalVariables - This works by removing the global
99 /// variable's initializer and seeing if the program still crashes. If it
100 /// does, then we keep that program and try again.
102 class ReduceCrashingGlobalVariables
: public ListReducer
<GlobalVariable
*> {
104 bool (*TestFn
)(BugDriver
&, Module
*);
106 ReduceCrashingGlobalVariables(BugDriver
&bd
,
107 bool (*testFn
)(BugDriver
&, Module
*))
108 : BD(bd
), TestFn(testFn
) {}
110 virtual TestResult
doTest(std::vector
<GlobalVariable
*>& Prefix
,
111 std::vector
<GlobalVariable
*>& Kept
) {
112 if (!Kept
.empty() && TestGlobalVariables(Kept
))
115 if (!Prefix
.empty() && TestGlobalVariables(Prefix
))
121 bool TestGlobalVariables(std::vector
<GlobalVariable
*>& GVs
);
126 ReduceCrashingGlobalVariables::TestGlobalVariables(
127 std::vector
<GlobalVariable
*>& GVs
) {
128 // Clone the program to try hacking it apart...
129 DenseMap
<const Value
*, Value
*> ValueMap
;
130 Module
*M
= CloneModule(BD
.getProgram(), ValueMap
);
132 // Convert list to set for fast lookup...
133 std::set
<GlobalVariable
*> GVSet
;
135 for (unsigned i
= 0, e
= GVs
.size(); i
!= e
; ++i
) {
136 GlobalVariable
* CMGV
= cast
<GlobalVariable
>(ValueMap
[GVs
[i
]]);
137 assert(CMGV
&& "Global Variable not in module?!");
141 std::cout
<< "Checking for crash with only these global variables: ";
142 PrintGlobalVariableList(GVs
);
145 // Loop over and delete any global variables which we aren't supposed to be
147 for (Module::global_iterator I
= M
->global_begin(), E
= M
->global_end();
149 if (I
->hasInitializer()) {
150 I
->setInitializer(0);
151 I
->setLinkage(GlobalValue::ExternalLinkage
);
154 // Try running the hacked up program...
156 BD
.setNewProgram(M
); // It crashed, keep the trimmed version...
158 // Make sure to use global variable pointers that point into the now-current
160 GVs
.assign(GVSet
.begin(), GVSet
.end());
169 /// ReduceCrashingFunctions reducer - This works by removing functions and
170 /// seeing if the program still crashes. If it does, then keep the newer,
173 class ReduceCrashingFunctions
: public ListReducer
<Function
*> {
175 bool (*TestFn
)(BugDriver
&, Module
*);
177 ReduceCrashingFunctions(BugDriver
&bd
,
178 bool (*testFn
)(BugDriver
&, Module
*))
179 : BD(bd
), TestFn(testFn
) {}
181 virtual TestResult
doTest(std::vector
<Function
*> &Prefix
,
182 std::vector
<Function
*> &Kept
) {
183 if (!Kept
.empty() && TestFuncs(Kept
))
185 if (!Prefix
.empty() && TestFuncs(Prefix
))
190 bool TestFuncs(std::vector
<Function
*> &Prefix
);
194 bool ReduceCrashingFunctions::TestFuncs(std::vector
<Function
*> &Funcs
) {
196 //if main isn't present, claim there is no problem
197 if (KeepMain
&& find(Funcs
.begin(), Funcs
.end(),
198 BD
.getProgram()->getFunction("main")) == Funcs
.end())
201 // Clone the program to try hacking it apart...
202 DenseMap
<const Value
*, Value
*> ValueMap
;
203 Module
*M
= CloneModule(BD
.getProgram(), ValueMap
);
205 // Convert list to set for fast lookup...
206 std::set
<Function
*> Functions
;
207 for (unsigned i
= 0, e
= Funcs
.size(); i
!= e
; ++i
) {
208 Function
*CMF
= cast
<Function
>(ValueMap
[Funcs
[i
]]);
209 assert(CMF
&& "Function not in module?!");
210 assert(CMF
->getFunctionType() == Funcs
[i
]->getFunctionType() && "wrong ty");
211 assert(CMF
->getName() == Funcs
[i
]->getName() && "wrong name");
212 Functions
.insert(CMF
);
215 std::cout
<< "Checking for crash with only these functions: ";
216 PrintFunctionList(Funcs
);
219 // Loop over and delete any functions which we aren't supposed to be playing
221 for (Module::iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
)
222 if (!I
->isDeclaration() && !Functions
.count(I
))
223 DeleteFunctionBody(I
);
225 // Try running the hacked up program...
227 BD
.setNewProgram(M
); // It crashed, keep the trimmed version...
229 // Make sure to use function pointers that point into the now-current
231 Funcs
.assign(Functions
.begin(), Functions
.end());
240 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
241 /// all terminators except the specified basic blocks to a 'ret' instruction,
242 /// then running the simplify-cfg pass. This has the effect of chopping up
243 /// the CFG really fast which can reduce large functions quickly.
245 class ReduceCrashingBlocks
: public ListReducer
<const BasicBlock
*> {
247 bool (*TestFn
)(BugDriver
&, Module
*);
249 ReduceCrashingBlocks(BugDriver
&bd
, bool (*testFn
)(BugDriver
&, Module
*))
250 : BD(bd
), TestFn(testFn
) {}
252 virtual TestResult
doTest(std::vector
<const BasicBlock
*> &Prefix
,
253 std::vector
<const BasicBlock
*> &Kept
) {
254 if (!Kept
.empty() && TestBlocks(Kept
))
256 if (!Prefix
.empty() && TestBlocks(Prefix
))
261 bool TestBlocks(std::vector
<const BasicBlock
*> &Prefix
);
265 bool ReduceCrashingBlocks::TestBlocks(std::vector
<const BasicBlock
*> &BBs
) {
266 // Clone the program to try hacking it apart...
267 DenseMap
<const Value
*, Value
*> ValueMap
;
268 Module
*M
= CloneModule(BD
.getProgram(), ValueMap
);
270 // Convert list to set for fast lookup...
271 SmallPtrSet
<BasicBlock
*, 8> Blocks
;
272 for (unsigned i
= 0, e
= BBs
.size(); i
!= e
; ++i
)
273 Blocks
.insert(cast
<BasicBlock
>(ValueMap
[BBs
[i
]]));
275 std::cout
<< "Checking for crash with only these blocks:";
276 unsigned NumPrint
= Blocks
.size();
277 if (NumPrint
> 10) NumPrint
= 10;
278 for (unsigned i
= 0, e
= NumPrint
; i
!= e
; ++i
)
279 std::cout
<< " " << BBs
[i
]->getName();
280 if (NumPrint
< Blocks
.size())
281 std::cout
<< "... <" << Blocks
.size() << " total>";
284 // Loop over and delete any hack up any blocks that are not listed...
285 for (Module::iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
)
286 for (Function::iterator BB
= I
->begin(), E
= I
->end(); BB
!= E
; ++BB
)
287 if (!Blocks
.count(BB
) && BB
->getTerminator()->getNumSuccessors()) {
288 // Loop over all of the successors of this block, deleting any PHI nodes
289 // that might include it.
290 for (succ_iterator SI
= succ_begin(BB
), E
= succ_end(BB
); SI
!= E
; ++SI
)
291 (*SI
)->removePredecessor(BB
);
293 TerminatorInst
*BBTerm
= BB
->getTerminator();
295 if (isa
<StructType
>(BBTerm
->getType()))
296 BBTerm
->replaceAllUsesWith(UndefValue::get(BBTerm
->getType()));
297 else if (BB
->getTerminator()->getType() != Type::VoidTy
)
298 BBTerm
->replaceAllUsesWith(Constant::getNullValue(BBTerm
->getType()));
300 // Replace the old terminator instruction.
301 BB
->getInstList().pop_back();
302 new UnreachableInst(BB
);
305 // The CFG Simplifier pass may delete one of the basic blocks we are
306 // interested in. If it does we need to take the block out of the list. Make
307 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
308 // This won't work well if blocks are unnamed, but that is just the risk we
310 std::vector
<std::pair
<Function
*, std::string
> > BlockInfo
;
312 for (SmallPtrSet
<BasicBlock
*, 8>::iterator I
= Blocks
.begin(),
313 E
= Blocks
.end(); I
!= E
; ++I
)
314 BlockInfo
.push_back(std::make_pair((*I
)->getParent(), (*I
)->getName()));
316 // Now run the CFG simplify pass on the function...
318 Passes
.add(createCFGSimplificationPass());
319 Passes
.add(createVerifierPass());
322 // Try running on the hacked up program...
324 BD
.setNewProgram(M
); // It crashed, keep the trimmed version...
326 // Make sure to use basic block pointers that point into the now-current
327 // module, and that they don't include any deleted blocks.
329 for (unsigned i
= 0, e
= BlockInfo
.size(); i
!= e
; ++i
) {
330 ValueSymbolTable
&ST
= BlockInfo
[i
].first
->getValueSymbolTable();
331 Value
* V
= ST
.lookup(BlockInfo
[i
].second
);
332 if (V
&& V
->getType() == Type::LabelTy
)
333 BBs
.push_back(cast
<BasicBlock
>(V
));
337 delete M
; // It didn't crash, try something else.
341 /// DebugACrash - Given a predicate that determines whether a component crashes
342 /// on a program, try to destructively reduce the program while still keeping
343 /// the predicate true.
344 static bool DebugACrash(BugDriver
&BD
, bool (*TestFn
)(BugDriver
&, Module
*)) {
345 // See if we can get away with nuking some of the global variable initializers
347 if (BD
.getProgram()->global_begin() != BD
.getProgram()->global_end()) {
348 // Now try to reduce the number of global variable initializers in the
349 // module to something small.
350 Module
*M
= CloneModule(BD
.getProgram());
351 bool DeletedInit
= false;
353 for (Module::global_iterator I
= M
->global_begin(), E
= M
->global_end();
355 if (I
->hasInitializer()) {
356 I
->setInitializer(0);
357 I
->setLinkage(GlobalValue::ExternalLinkage
);
362 delete M
; // No change made...
364 // See if the program still causes a crash...
365 std::cout
<< "\nChecking to see if we can delete global inits: ";
367 if (TestFn(BD
, M
)) { // Still crashes?
369 std::cout
<< "\n*** Able to remove all global initializers!\n";
370 } else { // No longer crashes?
371 std::cout
<< " - Removing all global inits hides problem!\n";
374 std::vector
<GlobalVariable
*> GVs
;
376 for (Module::global_iterator I
= BD
.getProgram()->global_begin(),
377 E
= BD
.getProgram()->global_end(); I
!= E
; ++I
)
378 if (I
->hasInitializer())
381 if (GVs
.size() > 1 && !BugpointIsInterrupted
) {
382 std::cout
<< "\n*** Attempting to reduce the number of global "
383 << "variables in the testcase\n";
385 unsigned OldSize
= GVs
.size();
386 ReduceCrashingGlobalVariables(BD
, TestFn
).reduceList(GVs
);
388 if (GVs
.size() < OldSize
)
389 BD
.EmitProgressBitcode("reduced-global-variables");
395 // Now try to reduce the number of functions in the module to something small.
396 std::vector
<Function
*> Functions
;
397 for (Module::iterator I
= BD
.getProgram()->begin(),
398 E
= BD
.getProgram()->end(); I
!= E
; ++I
)
399 if (!I
->isDeclaration())
400 Functions
.push_back(I
);
402 if (Functions
.size() > 1 && !BugpointIsInterrupted
) {
403 std::cout
<< "\n*** Attempting to reduce the number of functions "
406 unsigned OldSize
= Functions
.size();
407 ReduceCrashingFunctions(BD
, TestFn
).reduceList(Functions
);
409 if (Functions
.size() < OldSize
)
410 BD
.EmitProgressBitcode("reduced-function");
413 // Attempt to delete entire basic blocks at a time to speed up
414 // convergence... this actually works by setting the terminator of the blocks
415 // to a return instruction then running simplifycfg, which can potentially
416 // shrinks the code dramatically quickly
418 if (!DisableSimplifyCFG
&& !BugpointIsInterrupted
) {
419 std::vector
<const BasicBlock
*> Blocks
;
420 for (Module::const_iterator I
= BD
.getProgram()->begin(),
421 E
= BD
.getProgram()->end(); I
!= E
; ++I
)
422 for (Function::const_iterator FI
= I
->begin(), E
= I
->end(); FI
!=E
; ++FI
)
423 Blocks
.push_back(FI
);
424 ReduceCrashingBlocks(BD
, TestFn
).reduceList(Blocks
);
427 // FIXME: This should use the list reducer to converge faster by deleting
428 // larger chunks of instructions at a time!
429 unsigned Simplification
= 2;
431 if (BugpointIsInterrupted
) break;
433 std::cout
<< "\n*** Attempting to reduce testcase by deleting instruc"
434 << "tions: Simplification Level #" << Simplification
<< '\n';
436 // Now that we have deleted the functions that are unnecessary for the
437 // program, try to remove instructions that are not necessary to cause the
438 // crash. To do this, we loop through all of the instructions in the
439 // remaining functions, deleting them (replacing any values produced with
440 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
441 // still triggers failure, keep deleting until we cannot trigger failure
444 unsigned InstructionsToSkipBeforeDeleting
= 0;
447 // Loop over all of the (non-terminator) instructions remaining in the
448 // function, attempting to delete them.
449 unsigned CurInstructionNum
= 0;
450 for (Module::const_iterator FI
= BD
.getProgram()->begin(),
451 E
= BD
.getProgram()->end(); FI
!= E
; ++FI
)
452 if (!FI
->isDeclaration())
453 for (Function::const_iterator BI
= FI
->begin(), E
= FI
->end(); BI
!= E
;
455 for (BasicBlock::const_iterator I
= BI
->begin(), E
= --BI
->end();
456 I
!= E
; ++I
, ++CurInstructionNum
)
457 if (InstructionsToSkipBeforeDeleting
) {
458 --InstructionsToSkipBeforeDeleting
;
460 if (BugpointIsInterrupted
) goto ExitLoops
;
462 std::cout
<< "Checking instruction: " << *I
;
463 Module
*M
= BD
.deleteInstructionFromProgram(I
, Simplification
);
465 // Find out if the pass still crashes on this pass...
467 // Yup, it does, we delete the old module, and continue trying
468 // to reduce the testcase...
470 InstructionsToSkipBeforeDeleting
= CurInstructionNum
;
471 goto TryAgain
; // I wish I had a multi-level break here!
474 // This pass didn't crash without this instruction, try the next
479 if (InstructionsToSkipBeforeDeleting
) {
480 InstructionsToSkipBeforeDeleting
= 0;
484 } while (Simplification
);
487 // Try to clean up the testcase by running funcresolve and globaldce...
488 if (!BugpointIsInterrupted
) {
489 std::cout
<< "\n*** Attempting to perform final cleanups: ";
490 Module
*M
= CloneModule(BD
.getProgram());
491 M
= BD
.performFinalCleanups(M
, true);
493 // Find out if the pass still crashes on the cleaned up program...
495 BD
.setNewProgram(M
); // Yup, it does, keep the reduced version...
501 BD
.EmitProgressBitcode("reduced-simplified");
506 static bool TestForOptimizerCrash(BugDriver
&BD
, Module
*M
) {
507 return BD
.runPasses(M
);
510 /// debugOptimizerCrash - This method is called when some pass crashes on input.
511 /// It attempts to prune down the testcase to something reasonable, and figure
512 /// out exactly which pass is crashing.
514 bool BugDriver::debugOptimizerCrash(const std::string
&ID
) {
515 std::cout
<< "\n*** Debugging optimizer crash!\n";
517 // Reduce the list of passes which causes the optimizer to crash...
518 if (!BugpointIsInterrupted
)
519 ReducePassList(*this).reduceList(PassesToRun
);
521 std::cout
<< "\n*** Found crashing pass"
522 << (PassesToRun
.size() == 1 ? ": " : "es: ")
523 << getPassesString(PassesToRun
) << '\n';
525 EmitProgressBitcode(ID
);
527 return DebugACrash(*this, TestForOptimizerCrash
);
530 static bool TestForCodeGenCrash(BugDriver
&BD
, Module
*M
) {
532 BD
.compileProgram(M
);
535 } catch (ToolExecutionError
&) {
536 std::cerr
<< "<crash>\n";
537 return true; // Tool is still crashing.
541 /// debugCodeGeneratorCrash - This method is called when the code generator
542 /// crashes on an input. It attempts to reduce the input as much as possible
543 /// while still causing the code generator to crash.
544 bool BugDriver::debugCodeGeneratorCrash() {
545 std::cerr
<< "*** Debugging code generator crash!\n";
547 return DebugACrash(*this, TestForCodeGenCrash
);