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 "ListReducer.h"
16 #include "ToolRunner.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include <set>
37 using namespace llvm;
38 
39 namespace {
40 cl::opt<bool> KeepMain("keep-main",
41                        cl::desc("Force function reduction to keep main"),
42                        cl::init(false));
43 cl::opt<bool> NoGlobalRM("disable-global-remove",
44                          cl::desc("Do not remove global variables"),
45                          cl::init(false));
46 
47 cl::opt<bool> ReplaceFuncsWithNull(
48     "replace-funcs-with-null",
49     cl::desc("When stubbing functions, replace all uses will null"),
50     cl::init(false));
51 cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
52                                  cl::desc("Skip pass list reduction steps"),
53                                  cl::init(false));
54 
55 cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
56                           cl::desc("Do not remove global named metadata"),
57                           cl::init(false));
58 cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
59                                cl::desc("Do not strip debug info metadata"),
60                                cl::init(false));
61 cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
62                                cl::desc("Do not strip debug type info metadata"),
63                                cl::init(false));
64 cl::opt<bool> VerboseErrors("verbose-errors",
65                             cl::desc("Print the output of crashing program"),
66                             cl::init(false));
67 }
68 
69 namespace llvm {
70 class ReducePassList : public ListReducer<std::string> {
71   BugDriver &BD;
72 
73 public:
74   ReducePassList(BugDriver &bd) : BD(bd) {}
75 
76   // Return true iff running the "removed" passes succeeds, and running the
77   // "Kept" passes fail when run on the output of the "removed" passes.  If we
78   // return true, we update the current module of bugpoint.
79   Expected<TestResult> doTest(std::vector<std::string> &Removed,
80                               std::vector<std::string> &Kept) override;
81 };
82 }
83 
84 Expected<ReducePassList::TestResult>
85 ReducePassList::doTest(std::vector<std::string> &Prefix,
86                        std::vector<std::string> &Suffix) {
87   std::string PrefixOutput;
88   Module *OrigProgram = nullptr;
89   if (!Prefix.empty()) {
90     outs() << "Checking to see if these passes crash: "
91            << getPassesString(Prefix) << ": ";
92     if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
93       return KeepPrefix;
94 
95     OrigProgram = BD.Program;
96 
97     BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
98     if (BD.Program == nullptr) {
99       errs() << BD.getToolName() << ": Error reading bitcode file '"
100              << PrefixOutput << "'!\n";
101       exit(1);
102     }
103     sys::fs::remove(PrefixOutput);
104   }
105 
106   outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
107          << ": ";
108 
109   if (BD.runPasses(BD.getProgram(), Suffix)) {
110     delete OrigProgram; // The suffix crashes alone...
111     return KeepSuffix;
112   }
113 
114   // Nothing failed, restore state...
115   if (OrigProgram) {
116     delete BD.Program;
117     BD.Program = OrigProgram;
118   }
119   return NoFailure;
120 }
121 
122 using BugTester = bool (*)(const BugDriver &, Module *);
123 
124 namespace {
125 /// ReduceCrashingGlobalInitializers - This works by removing global variable
126 /// initializers and seeing if the program still crashes. If it does, then we
127 /// keep that program and try again.
128 class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
129   BugDriver &BD;
130   BugTester TestFn;
131 
132 public:
133   ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
134       : BD(bd), TestFn(testFn) {}
135 
136   Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
137                               std::vector<GlobalVariable *> &Kept) override {
138     if (!Kept.empty() && TestGlobalVariables(Kept))
139       return KeepSuffix;
140     if (!Prefix.empty() && TestGlobalVariables(Prefix))
141       return KeepPrefix;
142     return NoFailure;
143   }
144 
145   bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
146 };
147 }
148 
149 bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
150     std::vector<GlobalVariable *> &GVs) {
151   // Clone the program to try hacking it apart...
152   ValueToValueMapTy VMap;
153   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
154 
155   // Convert list to set for fast lookup...
156   std::set<GlobalVariable *> GVSet;
157 
158   for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
159     GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
160     assert(CMGV && "Global Variable not in module?!");
161     GVSet.insert(CMGV);
162   }
163 
164   outs() << "Checking for crash with only these global variables: ";
165   PrintGlobalVariableList(GVs);
166   outs() << ": ";
167 
168   // Loop over and delete any global variables which we aren't supposed to be
169   // playing with...
170   for (GlobalVariable &I : M->globals())
171     if (I.hasInitializer() && !GVSet.count(&I)) {
172       DeleteGlobalInitializer(&I);
173       I.setLinkage(GlobalValue::ExternalLinkage);
174       I.setComdat(nullptr);
175     }
176 
177   // Try running the hacked up program...
178   if (TestFn(BD, M.get())) {
179     BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
180 
181     // Make sure to use global variable pointers that point into the now-current
182     // module.
183     GVs.assign(GVSet.begin(), GVSet.end());
184     return true;
185   }
186 
187   return false;
188 }
189 
190 namespace {
191 /// ReduceCrashingFunctions reducer - This works by removing functions and
192 /// seeing if the program still crashes. If it does, then keep the newer,
193 /// smaller program.
194 ///
195 class ReduceCrashingFunctions : public ListReducer<Function *> {
196   BugDriver &BD;
197   BugTester TestFn;
198 
199 public:
200   ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
201       : BD(bd), TestFn(testFn) {}
202 
203   Expected<TestResult> doTest(std::vector<Function *> &Prefix,
204                               std::vector<Function *> &Kept) override {
205     if (!Kept.empty() && TestFuncs(Kept))
206       return KeepSuffix;
207     if (!Prefix.empty() && TestFuncs(Prefix))
208       return KeepPrefix;
209     return NoFailure;
210   }
211 
212   bool TestFuncs(std::vector<Function *> &Prefix);
213 };
214 }
215 
216 static void RemoveFunctionReferences(Module *M, const char *Name) {
217   auto *UsedVar = M->getGlobalVariable(Name, true);
218   if (!UsedVar || !UsedVar->hasInitializer())
219     return;
220   if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
221     assert(UsedVar->use_empty());
222     UsedVar->eraseFromParent();
223     return;
224   }
225   auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
226   std::vector<Constant *> Used;
227   for (Value *V : OldUsedVal->operand_values()) {
228     Constant *Op = cast<Constant>(V->stripPointerCasts());
229     if (!Op->isNullValue()) {
230       Used.push_back(cast<Constant>(V));
231     }
232   }
233   auto *NewValElemTy = OldUsedVal->getType()->getElementType();
234   auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
235   auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
236   UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
237   UsedVar->setInitializer(NewUsedVal);
238 }
239 
240 bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
241   // If main isn't present, claim there is no problem.
242   if (KeepMain && !is_contained(Funcs, BD.getProgram()->getFunction("main")))
243     return false;
244 
245   // Clone the program to try hacking it apart...
246   ValueToValueMapTy VMap;
247   Module *M = CloneModule(BD.getProgram(), VMap).release();
248 
249   // Convert list to set for fast lookup...
250   std::set<Function *> Functions;
251   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
252     Function *CMF = cast<Function>(VMap[Funcs[i]]);
253     assert(CMF && "Function not in module?!");
254     assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
255     assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
256     Functions.insert(CMF);
257   }
258 
259   outs() << "Checking for crash with only these functions: ";
260   PrintFunctionList(Funcs);
261   outs() << ": ";
262   if (!ReplaceFuncsWithNull) {
263     // Loop over and delete any functions which we aren't supposed to be playing
264     // with...
265     for (Function &I : *M)
266       if (!I.isDeclaration() && !Functions.count(&I))
267         DeleteFunctionBody(&I);
268   } else {
269     std::vector<GlobalValue *> ToRemove;
270     // First, remove aliases to functions we're about to purge.
271     for (GlobalAlias &Alias : M->aliases()) {
272       GlobalObject *Root = Alias.getBaseObject();
273       Function *F = dyn_cast_or_null<Function>(Root);
274       if (F) {
275         if (Functions.count(F))
276           // We're keeping this function.
277           continue;
278       } else if (Root->isNullValue()) {
279         // This referenced a globalalias that we've already replaced,
280         // so we still need to replace this alias.
281       } else if (!F) {
282         // Not a function, therefore not something we mess with.
283         continue;
284       }
285 
286       PointerType *Ty = cast<PointerType>(Alias.getType());
287       Constant *Replacement = ConstantPointerNull::get(Ty);
288       Alias.replaceAllUsesWith(Replacement);
289       ToRemove.push_back(&Alias);
290     }
291 
292     for (Function &I : *M) {
293       if (!I.isDeclaration() && !Functions.count(&I)) {
294         PointerType *Ty = cast<PointerType>(I.getType());
295         Constant *Replacement = ConstantPointerNull::get(Ty);
296         I.replaceAllUsesWith(Replacement);
297         ToRemove.push_back(&I);
298       }
299     }
300 
301     for (auto *F : ToRemove) {
302       F->eraseFromParent();
303     }
304 
305     // Finally, remove any null members from any global intrinsic.
306     RemoveFunctionReferences(M, "llvm.used");
307     RemoveFunctionReferences(M, "llvm.compiler.used");
308   }
309   // Try running the hacked up program...
310   if (TestFn(BD, M)) {
311     BD.setNewProgram(M); // It crashed, keep the trimmed version...
312 
313     // Make sure to use function pointers that point into the now-current
314     // module.
315     Funcs.assign(Functions.begin(), Functions.end());
316     return true;
317   }
318   delete M;
319   return false;
320 }
321 
322 namespace {
323 /// Simplify the CFG without completely destroying it.
324 /// This is not well defined, but basically comes down to "try to eliminate
325 /// unreachable blocks and constant fold terminators without deciding that
326 /// certain undefined behavior cuts off the program at the legs".
327 void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
328   if (F.empty())
329     return;
330 
331   for (auto *BB : BBs) {
332     ConstantFoldTerminator(BB);
333     MergeBlockIntoPredecessor(BB);
334   }
335 
336   // Remove unreachable blocks
337   // removeUnreachableBlocks can't be used here, it will turn various
338   // undefined behavior into unreachables, but bugpoint was the thing that
339   // generated the undefined behavior, and we don't want it to kill the entire
340   // program.
341   SmallPtrSet<BasicBlock *, 16> Visited;
342   for (auto *BB : depth_first(&F.getEntryBlock()))
343     Visited.insert(BB);
344 
345   SmallVector<BasicBlock *, 16> Unreachable;
346   for (auto &BB : F)
347     if (!Visited.count(&BB))
348       Unreachable.push_back(&BB);
349 
350   // The dead BB's may be in a dead cycle or otherwise have references to each
351   // other.  Because of this, we have to drop all references first, then delete
352   // them all at once.
353   for (auto *BB : Unreachable) {
354     for (BasicBlock *Successor : successors(&*BB))
355       if (Visited.count(Successor))
356         Successor->removePredecessor(&*BB);
357     BB->dropAllReferences();
358   }
359   for (auto *BB : Unreachable)
360     BB->eraseFromParent();
361 }
362 /// ReduceCrashingBlocks reducer - This works by setting the terminators of
363 /// all terminators except the specified basic blocks to a 'ret' instruction,
364 /// then running the simplify-cfg pass.  This has the effect of chopping up
365 /// the CFG really fast which can reduce large functions quickly.
366 ///
367 class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
368   BugDriver &BD;
369   BugTester TestFn;
370 
371 public:
372   ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
373       : BD(BD), TestFn(testFn) {}
374 
375   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
376                               std::vector<const BasicBlock *> &Kept) override {
377     if (!Kept.empty() && TestBlocks(Kept))
378       return KeepSuffix;
379     if (!Prefix.empty() && TestBlocks(Prefix))
380       return KeepPrefix;
381     return NoFailure;
382   }
383 
384   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
385 };
386 }
387 
388 bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
389   // Clone the program to try hacking it apart...
390   ValueToValueMapTy VMap;
391   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
392 
393   // Convert list to set for fast lookup...
394   SmallPtrSet<BasicBlock *, 8> Blocks;
395   for (unsigned i = 0, e = BBs.size(); i != e; ++i)
396     Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
397 
398   outs() << "Checking for crash with only these blocks:";
399   unsigned NumPrint = Blocks.size();
400   if (NumPrint > 10)
401     NumPrint = 10;
402   for (unsigned i = 0, e = NumPrint; i != e; ++i)
403     outs() << " " << BBs[i]->getName();
404   if (NumPrint < Blocks.size())
405     outs() << "... <" << Blocks.size() << " total>";
406   outs() << ": ";
407 
408   // Loop over and delete any hack up any blocks that are not listed...
409   for (Function &F : M->functions()) {
410     for (BasicBlock &BB : F) {
411       if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
412         // Loop over all of the successors of this block, deleting any PHI nodes
413         // that might include it.
414         for (BasicBlock *Succ : successors(&BB))
415           Succ->removePredecessor(&BB);
416 
417         TerminatorInst *BBTerm = BB.getTerminator();
418         if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
419           continue;
420         if (!BBTerm->getType()->isVoidTy())
421           BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
422 
423         // Replace the old terminator instruction.
424         BB.getInstList().pop_back();
425         new UnreachableInst(BB.getContext(), &BB);
426       }
427     }
428   }
429 
430   // The CFG Simplifier pass may delete one of the basic blocks we are
431   // interested in.  If it does we need to take the block out of the list.  Make
432   // a "persistent mapping" by turning basic blocks into <function, name> pairs.
433   // This won't work well if blocks are unnamed, but that is just the risk we
434   // have to take. FIXME: Can we just name the blocks?
435   std::vector<std::pair<std::string, std::string>> BlockInfo;
436 
437   for (BasicBlock *BB : Blocks)
438     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
439 
440   SmallVector<BasicBlock *, 16> ToProcess;
441   for (auto &F : *M) {
442     for (auto &BB : F)
443       if (!Blocks.count(&BB))
444         ToProcess.push_back(&BB);
445     simpleSimplifyCfg(F, ToProcess);
446     ToProcess.clear();
447   }
448   // Verify we didn't break anything
449   std::vector<std::string> Passes;
450   Passes.push_back("verify");
451   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
452   if (!New) {
453     errs() << "verify failed!\n";
454     exit(1);
455   }
456   M = std::move(New);
457 
458   // Try running on the hacked up program...
459   if (TestFn(BD, M.get())) {
460     BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
461 
462     // Make sure to use basic block pointers that point into the now-current
463     // module, and that they don't include any deleted blocks.
464     BBs.clear();
465     const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
466     for (const auto &BI : BlockInfo) {
467       Function *F = cast<Function>(GST.lookup(BI.first));
468       Value *V = F->getValueSymbolTable()->lookup(BI.second);
469       if (V && V->getType() == Type::getLabelTy(V->getContext()))
470         BBs.push_back(cast<BasicBlock>(V));
471     }
472     return true;
473   }
474   // It didn't crash, try something else.
475   return false;
476 }
477 
478 namespace {
479 /// ReduceCrashingConditionals reducer - This works by changing
480 /// conditional branches to unconditional ones, then simplifying the CFG
481 /// This has the effect of chopping up the CFG really fast which can reduce
482 /// large functions quickly.
483 ///
484 class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
485   BugDriver &BD;
486   BugTester TestFn;
487   bool Direction;
488 
489 public:
490   ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
491       : BD(bd), TestFn(testFn), Direction(Direction) {}
492 
493   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
494                               std::vector<const BasicBlock *> &Kept) override {
495     if (!Kept.empty() && TestBlocks(Kept))
496       return KeepSuffix;
497     if (!Prefix.empty() && TestBlocks(Prefix))
498       return KeepPrefix;
499     return NoFailure;
500   }
501 
502   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
503 };
504 }
505 
506 bool ReduceCrashingConditionals::TestBlocks(
507     std::vector<const BasicBlock *> &BBs) {
508   // Clone the program to try hacking it apart...
509   ValueToValueMapTy VMap;
510   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
511 
512   // Convert list to set for fast lookup...
513   SmallPtrSet<const BasicBlock *, 8> Blocks;
514   for (const auto *BB : BBs)
515     Blocks.insert(cast<BasicBlock>(VMap[BB]));
516 
517   outs() << "Checking for crash with changing conditionals to always jump to "
518          << (Direction ? "true" : "false") << ":";
519   unsigned NumPrint = Blocks.size();
520   if (NumPrint > 10)
521     NumPrint = 10;
522   for (unsigned i = 0, e = NumPrint; i != e; ++i)
523     outs() << " " << BBs[i]->getName();
524   if (NumPrint < Blocks.size())
525     outs() << "... <" << Blocks.size() << " total>";
526   outs() << ": ";
527 
528   // Loop over and delete any hack up any blocks that are not listed...
529   for (auto &F : *M)
530     for (auto &BB : F)
531       if (!Blocks.count(&BB)) {
532         auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
533         if (!BR || !BR->isConditional())
534           continue;
535         if (Direction)
536           BR->setCondition(ConstantInt::getTrue(BR->getContext()));
537         else
538           BR->setCondition(ConstantInt::getFalse(BR->getContext()));
539       }
540 
541   // The following may destroy some blocks, so we save them first
542   std::vector<std::pair<std::string, std::string>> BlockInfo;
543 
544   for (const BasicBlock *BB : Blocks)
545     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
546 
547   SmallVector<BasicBlock *, 16> ToProcess;
548   for (auto &F : *M) {
549     for (auto &BB : F)
550       if (!Blocks.count(&BB))
551         ToProcess.push_back(&BB);
552     simpleSimplifyCfg(F, ToProcess);
553     ToProcess.clear();
554   }
555   // Verify we didn't break anything
556   std::vector<std::string> Passes;
557   Passes.push_back("verify");
558   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
559   if (!New) {
560     errs() << "verify failed!\n";
561     exit(1);
562   }
563   M = std::move(New);
564 
565   // Try running on the hacked up program...
566   if (TestFn(BD, M.get())) {
567     BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
568 
569     // Make sure to use basic block pointers that point into the now-current
570     // module, and that they don't include any deleted blocks.
571     BBs.clear();
572     const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
573     for (auto &BI : BlockInfo) {
574       auto *F = cast<Function>(GST.lookup(BI.first));
575       Value *V = F->getValueSymbolTable()->lookup(BI.second);
576       if (V && V->getType() == Type::getLabelTy(V->getContext()))
577         BBs.push_back(cast<BasicBlock>(V));
578     }
579     return true;
580   }
581   // It didn't crash, try something else.
582   return false;
583 }
584 
585 namespace {
586 /// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
587 /// in the program.
588 
589 class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
590   BugDriver &BD;
591   BugTester TestFn;
592   TargetTransformInfo TTI;
593 
594 public:
595   ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
596       : BD(bd), TestFn(testFn), TTI(bd.getProgram()->getDataLayout()) {}
597 
598   Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
599                               std::vector<const BasicBlock *> &Kept) override {
600     if (!Kept.empty() && TestBlocks(Kept))
601       return KeepSuffix;
602     if (!Prefix.empty() && TestBlocks(Prefix))
603       return KeepPrefix;
604     return NoFailure;
605   }
606 
607   bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
608 };
609 }
610 
611 bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
612   // Clone the program to try hacking it apart...
613   ValueToValueMapTy VMap;
614   std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
615 
616   // Convert list to set for fast lookup...
617   SmallPtrSet<const BasicBlock *, 8> Blocks;
618   for (const auto *BB : BBs)
619     Blocks.insert(cast<BasicBlock>(VMap[BB]));
620 
621   outs() << "Checking for crash with CFG simplifying:";
622   unsigned NumPrint = Blocks.size();
623   if (NumPrint > 10)
624     NumPrint = 10;
625   for (unsigned i = 0, e = NumPrint; i != e; ++i)
626     outs() << " " << BBs[i]->getName();
627   if (NumPrint < Blocks.size())
628     outs() << "... <" << Blocks.size() << " total>";
629   outs() << ": ";
630 
631   // The following may destroy some blocks, so we save them first
632   std::vector<std::pair<std::string, std::string>> BlockInfo;
633 
634   for (const BasicBlock *BB : Blocks)
635     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
636 
637   // Loop over and delete any hack up any blocks that are not listed...
638   for (auto &F : *M)
639     // Loop over all of the basic blocks and remove them if they are unneeded.
640     for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
641       if (!Blocks.count(&*BBIt)) {
642         ++BBIt;
643         continue;
644       }
645       simplifyCFG(&*BBIt++, TTI);
646     }
647   // Verify we didn't break anything
648   std::vector<std::string> Passes;
649   Passes.push_back("verify");
650   std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
651   if (!New) {
652     errs() << "verify failed!\n";
653     exit(1);
654   }
655   M = std::move(New);
656 
657   // Try running on the hacked up program...
658   if (TestFn(BD, M.get())) {
659     BD.setNewProgram(M.release()); // It crashed, keep the trimmed version...
660 
661     // Make sure to use basic block pointers that point into the now-current
662     // module, and that they don't include any deleted blocks.
663     BBs.clear();
664     const ValueSymbolTable &GST = BD.getProgram()->getValueSymbolTable();
665     for (auto &BI : BlockInfo) {
666       auto *F = cast<Function>(GST.lookup(BI.first));
667       Value *V = F->getValueSymbolTable()->lookup(BI.second);
668       if (V && V->getType() == Type::getLabelTy(V->getContext()))
669         BBs.push_back(cast<BasicBlock>(V));
670     }
671     return true;
672   }
673   // It didn't crash, try something else.
674   return false;
675 }
676 
677 namespace {
678 /// ReduceCrashingInstructions reducer - This works by removing the specified
679 /// non-terminator instructions and replacing them with undef.
680 ///
681 class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
682   BugDriver &BD;
683   BugTester TestFn;
684 
685 public:
686   ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
687       : BD(bd), TestFn(testFn) {}
688 
689   Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
690                               std::vector<const Instruction *> &Kept) override {
691     if (!Kept.empty() && TestInsts(Kept))
692       return KeepSuffix;
693     if (!Prefix.empty() && TestInsts(Prefix))
694       return KeepPrefix;
695     return NoFailure;
696   }
697 
698   bool TestInsts(std::vector<const Instruction *> &Prefix);
699 };
700 }
701 
702 bool ReduceCrashingInstructions::TestInsts(
703     std::vector<const Instruction *> &Insts) {
704   // Clone the program to try hacking it apart...
705   ValueToValueMapTy VMap;
706   Module *M = CloneModule(BD.getProgram(), VMap).release();
707 
708   // Convert list to set for fast lookup...
709   SmallPtrSet<Instruction *, 32> Instructions;
710   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
711     assert(!isa<TerminatorInst>(Insts[i]));
712     Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
713   }
714 
715   outs() << "Checking for crash with only " << Instructions.size();
716   if (Instructions.size() == 1)
717     outs() << " instruction: ";
718   else
719     outs() << " instructions: ";
720 
721   for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
722     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
723       for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
724         Instruction *Inst = &*I++;
725         if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
726             !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
727             !Inst->isSwiftError()) {
728           if (!Inst->getType()->isVoidTy())
729             Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
730           Inst->eraseFromParent();
731         }
732       }
733 
734   // Verify that this is still valid.
735   legacy::PassManager Passes;
736   Passes.add(createVerifierPass(/*FatalErrors=*/false));
737   Passes.run(*M);
738 
739   // Try running on the hacked up program...
740   if (TestFn(BD, M)) {
741     BD.setNewProgram(M); // It crashed, keep the trimmed version...
742 
743     // Make sure to use instruction pointers that point into the now-current
744     // module, and that they don't include any deleted blocks.
745     Insts.clear();
746     for (Instruction *Inst : Instructions)
747       Insts.push_back(Inst);
748     return true;
749   }
750   delete M; // It didn't crash, try something else.
751   return false;
752 }
753 
754 namespace {
755 // Reduce the list of Named Metadata nodes. We keep this as a list of
756 // names to avoid having to convert back and forth every time.
757 class ReduceCrashingNamedMD : public ListReducer<std::string> {
758   BugDriver &BD;
759   BugTester TestFn;
760 
761 public:
762   ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
763       : BD(bd), TestFn(testFn) {}
764 
765   Expected<TestResult> doTest(std::vector<std::string> &Prefix,
766                               std::vector<std::string> &Kept) override {
767     if (!Kept.empty() && TestNamedMDs(Kept))
768       return KeepSuffix;
769     if (!Prefix.empty() && TestNamedMDs(Prefix))
770       return KeepPrefix;
771     return NoFailure;
772   }
773 
774   bool TestNamedMDs(std::vector<std::string> &NamedMDs);
775 };
776 }
777 
778 bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
779 
780   ValueToValueMapTy VMap;
781   Module *M = CloneModule(BD.getProgram(), VMap).release();
782 
783   outs() << "Checking for crash with only these named metadata nodes:";
784   unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
785   for (unsigned i = 0, e = NumPrint; i != e; ++i)
786     outs() << " " << NamedMDs[i];
787   if (NumPrint < NamedMDs.size())
788     outs() << "... <" << NamedMDs.size() << " total>";
789   outs() << ": ";
790 
791   // Make a StringMap for faster lookup
792   StringSet<> Names;
793   for (const std::string &Name : NamedMDs)
794     Names.insert(Name);
795 
796   // First collect all the metadata to delete in a vector, then
797   // delete them all at once to avoid invalidating the iterator
798   std::vector<NamedMDNode *> ToDelete;
799   ToDelete.reserve(M->named_metadata_size() - Names.size());
800   for (auto &NamedMD : M->named_metadata())
801     // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
802     if (!Names.count(NamedMD.getName()) &&
803         (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
804       ToDelete.push_back(&NamedMD);
805 
806   for (auto *NamedMD : ToDelete)
807     NamedMD->eraseFromParent();
808 
809   // Verify that this is still valid.
810   legacy::PassManager Passes;
811   Passes.add(createVerifierPass(/*FatalErrors=*/false));
812   Passes.run(*M);
813 
814   // Try running on the hacked up program...
815   if (TestFn(BD, M)) {
816     BD.setNewProgram(M); // It crashed, keep the trimmed version...
817     return true;
818   }
819   delete M; // It didn't crash, try something else.
820   return false;
821 }
822 
823 namespace {
824 // Reduce the list of operands to named metadata nodes
825 class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
826   BugDriver &BD;
827   BugTester TestFn;
828 
829 public:
830   ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
831       : BD(bd), TestFn(testFn) {}
832 
833   Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
834                               std::vector<const MDNode *> &Kept) override {
835     if (!Kept.empty() && TestNamedMDOps(Kept))
836       return KeepSuffix;
837     if (!Prefix.empty() && TestNamedMDOps(Prefix))
838       return KeepPrefix;
839     return NoFailure;
840   }
841 
842   bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
843 };
844 }
845 
846 bool ReduceCrashingNamedMDOps::TestNamedMDOps(
847     std::vector<const MDNode *> &NamedMDOps) {
848   // Convert list to set for fast lookup...
849   SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
850   for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
851     OldMDNodeOps.insert(NamedMDOps[i]);
852   }
853 
854   outs() << "Checking for crash with only " << OldMDNodeOps.size();
855   if (OldMDNodeOps.size() == 1)
856     outs() << " named metadata operand: ";
857   else
858     outs() << " named metadata operands: ";
859 
860   ValueToValueMapTy VMap;
861   Module *M = CloneModule(BD.getProgram(), VMap).release();
862 
863   // This is a little wasteful. In the future it might be good if we could have
864   // these dropped during cloning.
865   for (auto &NamedMD : BD.getProgram()->named_metadata()) {
866     // Drop the old one and create a new one
867     M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
868     NamedMDNode *NewNamedMDNode =
869         M->getOrInsertNamedMetadata(NamedMD.getName());
870     for (MDNode *op : NamedMD.operands())
871       if (OldMDNodeOps.count(op))
872         NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
873   }
874 
875   // Verify that this is still valid.
876   legacy::PassManager Passes;
877   Passes.add(createVerifierPass(/*FatalErrors=*/false));
878   Passes.run(*M);
879 
880   // Try running on the hacked up program...
881   if (TestFn(BD, M)) {
882     // Make sure to use instruction pointers that point into the now-current
883     // module, and that they don't include any deleted blocks.
884     NamedMDOps.clear();
885     for (const MDNode *Node : OldMDNodeOps)
886       NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
887 
888     BD.setNewProgram(M); // It crashed, keep the trimmed version...
889     return true;
890   }
891   delete M; // It didn't crash, try something else.
892   return false;
893 }
894 
895 /// Attempt to eliminate as many global initializers as possible.
896 static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
897   Module *OrigM = BD.getProgram();
898   if (OrigM->global_empty())
899     return Error::success();
900 
901   // Now try to reduce the number of global variable initializers in the
902   // module to something small.
903   std::unique_ptr<Module> M = CloneModule(OrigM);
904   bool DeletedInit = false;
905 
906   for (GlobalVariable &GV : M->globals()) {
907     if (GV.hasInitializer()) {
908       DeleteGlobalInitializer(&GV);
909       GV.setLinkage(GlobalValue::ExternalLinkage);
910       GV.setComdat(nullptr);
911       DeletedInit = true;
912     }
913   }
914 
915   if (!DeletedInit)
916     return Error::success();
917 
918   // See if the program still causes a crash...
919   outs() << "\nChecking to see if we can delete global inits: ";
920 
921   if (TestFn(BD, M.get())) { // Still crashes?
922     BD.setNewProgram(M.release());
923     outs() << "\n*** Able to remove all global initializers!\n";
924     return Error::success();
925   }
926 
927   // No longer crashes.
928   outs() << "  - Removing all global inits hides problem!\n";
929 
930   std::vector<GlobalVariable *> GVs;
931   for (GlobalVariable &GV : OrigM->globals())
932     if (GV.hasInitializer())
933       GVs.push_back(&GV);
934 
935   if (GVs.size() > 1 && !BugpointIsInterrupted) {
936     outs() << "\n*** Attempting to reduce the number of global initializers "
937            << "in the testcase\n";
938 
939     unsigned OldSize = GVs.size();
940     Expected<bool> Result =
941         ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
942     if (Error E = Result.takeError())
943       return E;
944 
945     if (GVs.size() < OldSize)
946       BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
947   }
948   return Error::success();
949 }
950 
951 static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
952   // Attempt to delete instructions using bisection. This should help out nasty
953   // cases with large basic blocks where the problem is at one end.
954   if (!BugpointIsInterrupted) {
955     std::vector<const Instruction *> Insts;
956     for (const Function &F : *BD.getProgram())
957       for (const BasicBlock &BB : F)
958         for (const Instruction &I : BB)
959           if (!isa<TerminatorInst>(&I))
960             Insts.push_back(&I);
961 
962     Expected<bool> Result =
963         ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
964     if (Error E = Result.takeError())
965       return E;
966   }
967 
968   unsigned Simplification = 2;
969   do {
970     if (BugpointIsInterrupted)
971       // TODO: Should we distinguish this with an "interrupted error"?
972       return Error::success();
973     --Simplification;
974     outs() << "\n*** Attempting to reduce testcase by deleting instruc"
975            << "tions: Simplification Level #" << Simplification << '\n';
976 
977     // Now that we have deleted the functions that are unnecessary for the
978     // program, try to remove instructions that are not necessary to cause the
979     // crash.  To do this, we loop through all of the instructions in the
980     // remaining functions, deleting them (replacing any values produced with
981     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
982     // still triggers failure, keep deleting until we cannot trigger failure
983     // anymore.
984     //
985     unsigned InstructionsToSkipBeforeDeleting = 0;
986   TryAgain:
987 
988     // Loop over all of the (non-terminator) instructions remaining in the
989     // function, attempting to delete them.
990     unsigned CurInstructionNum = 0;
991     for (Module::const_iterator FI = BD.getProgram()->begin(),
992                                 E = BD.getProgram()->end();
993          FI != E; ++FI)
994       if (!FI->isDeclaration())
995         for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
996              ++BI)
997           for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
998                I != E; ++I, ++CurInstructionNum) {
999             if (InstructionsToSkipBeforeDeleting) {
1000               --InstructionsToSkipBeforeDeleting;
1001             } else {
1002               if (BugpointIsInterrupted)
1003                 // TODO: Should this be some kind of interrupted error?
1004                 return Error::success();
1005 
1006               if (I->isEHPad() || I->getType()->isTokenTy() ||
1007                   I->isSwiftError())
1008                 continue;
1009 
1010               outs() << "Checking instruction: " << *I;
1011               std::unique_ptr<Module> M =
1012                   BD.deleteInstructionFromProgram(&*I, Simplification);
1013 
1014               // Find out if the pass still crashes on this pass...
1015               if (TestFn(BD, M.get())) {
1016                 // Yup, it does, we delete the old module, and continue trying
1017                 // to reduce the testcase...
1018                 BD.setNewProgram(M.release());
1019                 InstructionsToSkipBeforeDeleting = CurInstructionNum;
1020                 goto TryAgain; // I wish I had a multi-level break here!
1021               }
1022             }
1023           }
1024 
1025     if (InstructionsToSkipBeforeDeleting) {
1026       InstructionsToSkipBeforeDeleting = 0;
1027       goto TryAgain;
1028     }
1029 
1030   } while (Simplification);
1031   BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
1032   return Error::success();
1033 }
1034 
1035 /// DebugACrash - Given a predicate that determines whether a component crashes
1036 /// on a program, try to destructively reduce the program while still keeping
1037 /// the predicate true.
1038 static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
1039   // See if we can get away with nuking some of the global variable initializers
1040   // in the program...
1041   if (!NoGlobalRM)
1042     if (Error E = ReduceGlobalInitializers(BD, TestFn))
1043       return E;
1044 
1045   // Now try to reduce the number of functions in the module to something small.
1046   std::vector<Function *> Functions;
1047   for (Function &F : *BD.getProgram())
1048     if (!F.isDeclaration())
1049       Functions.push_back(&F);
1050 
1051   if (Functions.size() > 1 && !BugpointIsInterrupted) {
1052     outs() << "\n*** Attempting to reduce the number of functions "
1053               "in the testcase\n";
1054 
1055     unsigned OldSize = Functions.size();
1056     Expected<bool> Result =
1057         ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1058     if (Error E = Result.takeError())
1059       return E;
1060 
1061     if (Functions.size() < OldSize)
1062       BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
1063   }
1064 
1065   // Attempt to change conditional branches into unconditional branches to
1066   // eliminate blocks.
1067   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1068     std::vector<const BasicBlock *> Blocks;
1069     for (Function &F : *BD.getProgram())
1070       for (BasicBlock &BB : F)
1071         Blocks.push_back(&BB);
1072     unsigned OldSize = Blocks.size();
1073     Expected<bool> Result =
1074         ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1075     if (Error E = Result.takeError())
1076       return E;
1077     Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1078     if (Error E = Result.takeError())
1079       return E;
1080     if (Blocks.size() < OldSize)
1081       BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1082   }
1083 
1084   // Attempt to delete entire basic blocks at a time to speed up
1085   // convergence... this actually works by setting the terminator of the blocks
1086   // to a return instruction then running simplifycfg, which can potentially
1087   // shrinks the code dramatically quickly
1088   //
1089   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1090     std::vector<const BasicBlock *> Blocks;
1091     for (Function &F : *BD.getProgram())
1092       for (BasicBlock &BB : F)
1093         Blocks.push_back(&BB);
1094     unsigned OldSize = Blocks.size();
1095     Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1096     if (Error E = Result.takeError())
1097       return E;
1098     if (Blocks.size() < OldSize)
1099       BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
1100   }
1101 
1102   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
1103     std::vector<const BasicBlock *> Blocks;
1104     for (Function &F : *BD.getProgram())
1105       for (BasicBlock &BB : F)
1106         Blocks.push_back(&BB);
1107     unsigned OldSize = Blocks.size();
1108     Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1109     if (Error E = Result.takeError())
1110       return E;
1111     if (Blocks.size() < OldSize)
1112       BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1113   }
1114 
1115   // Attempt to delete instructions using bisection. This should help out nasty
1116   // cases with large basic blocks where the problem is at one end.
1117   if (!BugpointIsInterrupted)
1118     if (Error E = ReduceInsts(BD, TestFn))
1119       return E;
1120 
1121   // Attempt to strip debug info metadata.
1122   auto stripMetadata = [&](std::function<bool(Module &)> strip) {
1123     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1124     strip(*M);
1125     if (TestFn(BD, M.get()))
1126       BD.setNewProgram(M.release());
1127   };
1128   if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1129     outs() << "\n*** Attempting to strip the debug info: ";
1130     stripMetadata(StripDebugInfo);
1131   }
1132   if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1133     outs() << "\n*** Attempting to strip the debug type info: ";
1134     stripMetadata(stripNonLineTableDebugInfo);
1135   }
1136 
1137   if (!NoNamedMDRM) {
1138     if (!BugpointIsInterrupted) {
1139       // Try to reduce the amount of global metadata (particularly debug info),
1140       // by dropping global named metadata that anchors them
1141       outs() << "\n*** Attempting to remove named metadata: ";
1142       std::vector<std::string> NamedMDNames;
1143       for (auto &NamedMD : BD.getProgram()->named_metadata())
1144         NamedMDNames.push_back(NamedMD.getName().str());
1145       Expected<bool> Result =
1146           ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1147       if (Error E = Result.takeError())
1148         return E;
1149     }
1150 
1151     if (!BugpointIsInterrupted) {
1152       // Now that we quickly dropped all the named metadata that doesn't
1153       // contribute to the crash, bisect the operands of the remaining ones
1154       std::vector<const MDNode *> NamedMDOps;
1155       for (auto &NamedMD : BD.getProgram()->named_metadata())
1156         for (auto op : NamedMD.operands())
1157           NamedMDOps.push_back(op);
1158       Expected<bool> Result =
1159           ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1160       if (Error E = Result.takeError())
1161         return E;
1162     }
1163     BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
1164   }
1165 
1166   // Try to clean up the testcase by running funcresolve and globaldce...
1167   if (!BugpointIsInterrupted) {
1168     outs() << "\n*** Attempting to perform final cleanups: ";
1169     std::unique_ptr<Module> M = CloneModule(BD.getProgram());
1170     M = BD.performFinalCleanups(M.release(), true);
1171 
1172     // Find out if the pass still crashes on the cleaned up program...
1173     if (M && TestFn(BD, M.get()))
1174       BD.setNewProgram(M.release()); // Yup, it does, keep the reduced version...
1175   }
1176 
1177   BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
1178 
1179   return Error::success();
1180 }
1181 
1182 static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
1183   return BD.runPasses(M, BD.getPassesToRun());
1184 }
1185 
1186 /// debugOptimizerCrash - This method is called when some pass crashes on input.
1187 /// It attempts to prune down the testcase to something reasonable, and figure
1188 /// out exactly which pass is crashing.
1189 ///
1190 Error BugDriver::debugOptimizerCrash(const std::string &ID) {
1191   outs() << "\n*** Debugging optimizer crash!\n";
1192 
1193   // Reduce the list of passes which causes the optimizer to crash...
1194   if (!BugpointIsInterrupted && !DontReducePassList) {
1195     Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1196     if (Error E = Result.takeError())
1197       return E;
1198   }
1199 
1200   outs() << "\n*** Found crashing pass"
1201          << (PassesToRun.size() == 1 ? ": " : "es: ")
1202          << getPassesString(PassesToRun) << '\n';
1203 
1204   EmitProgressBitcode(Program, ID);
1205 
1206   return DebugACrash(*this, TestForOptimizerCrash);
1207 }
1208 
1209 static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
1210   if (Error E = BD.compileProgram(M)) {
1211     if (VerboseErrors)
1212       errs() << toString(std::move(E)) << "\n";
1213     else {
1214       consumeError(std::move(E));
1215       errs() << "<crash>\n";
1216     }
1217     return true; // Tool is still crashing.
1218   }
1219   errs() << '\n';
1220   return false;
1221 }
1222 
1223 /// debugCodeGeneratorCrash - This method is called when the code generator
1224 /// crashes on an input.  It attempts to reduce the input as much as possible
1225 /// while still causing the code generator to crash.
1226 Error BugDriver::debugCodeGeneratorCrash() {
1227   errs() << "*** Debugging code generator crash!\n";
1228 
1229   return DebugACrash(*this, TestForCodeGenCrash);
1230 }
1231