xref: /aosp_15_r20/external/llvm/tools/bugpoint/CrashDebugger.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file defines the bugpoint internals that narrow down compilation crashes
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker 
14*9880d681SAndroid Build Coastguard Worker #include "BugDriver.h"
15*9880d681SAndroid Build Coastguard Worker #include "ListReducer.h"
16*9880d681SAndroid Build Coastguard Worker #include "ToolRunner.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringSet.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LegacyPassManager.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueSymbolTable.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Verifier.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/FileUtilities.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Cloning.h"
32*9880d681SAndroid Build Coastguard Worker #include <set>
33*9880d681SAndroid Build Coastguard Worker using namespace llvm;
34*9880d681SAndroid Build Coastguard Worker 
35*9880d681SAndroid Build Coastguard Worker namespace {
36*9880d681SAndroid Build Coastguard Worker   cl::opt<bool>
37*9880d681SAndroid Build Coastguard Worker   KeepMain("keep-main",
38*9880d681SAndroid Build Coastguard Worker            cl::desc("Force function reduction to keep main"),
39*9880d681SAndroid Build Coastguard Worker            cl::init(false));
40*9880d681SAndroid Build Coastguard Worker   cl::opt<bool>
41*9880d681SAndroid Build Coastguard Worker   NoGlobalRM ("disable-global-remove",
42*9880d681SAndroid Build Coastguard Worker          cl::desc("Do not remove global variables"),
43*9880d681SAndroid Build Coastguard Worker          cl::init(false));
44*9880d681SAndroid Build Coastguard Worker 
45*9880d681SAndroid Build Coastguard Worker   cl::opt<bool>
46*9880d681SAndroid Build Coastguard Worker   ReplaceFuncsWithNull("replace-funcs-with-null",
47*9880d681SAndroid Build Coastguard Worker          cl::desc("When stubbing functions, replace all uses will null"),
48*9880d681SAndroid Build Coastguard Worker          cl::init(false));
49*9880d681SAndroid Build Coastguard Worker   cl::opt<bool>
50*9880d681SAndroid Build Coastguard Worker   DontReducePassList("disable-pass-list-reduction",
51*9880d681SAndroid Build Coastguard Worker                      cl::desc("Skip pass list reduction steps"),
52*9880d681SAndroid Build Coastguard Worker                      cl::init(false));
53*9880d681SAndroid Build Coastguard Worker 
54*9880d681SAndroid Build Coastguard Worker   cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
55*9880d681SAndroid Build Coastguard Worker                             cl::desc("Do not remove global named metadata"),
56*9880d681SAndroid Build Coastguard Worker                             cl::init(false));
57*9880d681SAndroid Build Coastguard Worker }
58*9880d681SAndroid Build Coastguard Worker 
59*9880d681SAndroid Build Coastguard Worker namespace llvm {
60*9880d681SAndroid Build Coastguard Worker   class ReducePassList : public ListReducer<std::string> {
61*9880d681SAndroid Build Coastguard Worker     BugDriver &BD;
62*9880d681SAndroid Build Coastguard Worker   public:
ReducePassList(BugDriver & bd)63*9880d681SAndroid Build Coastguard Worker     ReducePassList(BugDriver &bd) : BD(bd) {}
64*9880d681SAndroid Build Coastguard Worker 
65*9880d681SAndroid Build Coastguard Worker     // doTest - Return true iff running the "removed" passes succeeds, and
66*9880d681SAndroid Build Coastguard Worker     // running the "Kept" passes fail when run on the output of the "removed"
67*9880d681SAndroid Build Coastguard Worker     // passes.  If we return true, we update the current module of bugpoint.
68*9880d681SAndroid Build Coastguard Worker     //
69*9880d681SAndroid Build Coastguard Worker     TestResult doTest(std::vector<std::string> &Removed,
70*9880d681SAndroid Build Coastguard Worker                       std::vector<std::string> &Kept,
71*9880d681SAndroid Build Coastguard Worker                       std::string &Error) override;
72*9880d681SAndroid Build Coastguard Worker   };
73*9880d681SAndroid Build Coastguard Worker }
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker ReducePassList::TestResult
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Suffix,std::string & Error)76*9880d681SAndroid Build Coastguard Worker ReducePassList::doTest(std::vector<std::string> &Prefix,
77*9880d681SAndroid Build Coastguard Worker                        std::vector<std::string> &Suffix,
78*9880d681SAndroid Build Coastguard Worker                        std::string &Error) {
79*9880d681SAndroid Build Coastguard Worker   std::string PrefixOutput;
80*9880d681SAndroid Build Coastguard Worker   Module *OrigProgram = nullptr;
81*9880d681SAndroid Build Coastguard Worker   if (!Prefix.empty()) {
82*9880d681SAndroid Build Coastguard Worker     outs() << "Checking to see if these passes crash: "
83*9880d681SAndroid Build Coastguard Worker            << getPassesString(Prefix) << ": ";
84*9880d681SAndroid Build Coastguard Worker     if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
85*9880d681SAndroid Build Coastguard Worker       return KeepPrefix;
86*9880d681SAndroid Build Coastguard Worker 
87*9880d681SAndroid Build Coastguard Worker     OrigProgram = BD.Program;
88*9880d681SAndroid Build Coastguard Worker 
89*9880d681SAndroid Build Coastguard Worker     BD.Program = parseInputFile(PrefixOutput, BD.getContext()).release();
90*9880d681SAndroid Build Coastguard Worker     if (BD.Program == nullptr) {
91*9880d681SAndroid Build Coastguard Worker       errs() << BD.getToolName() << ": Error reading bitcode file '"
92*9880d681SAndroid Build Coastguard Worker              << PrefixOutput << "'!\n";
93*9880d681SAndroid Build Coastguard Worker       exit(1);
94*9880d681SAndroid Build Coastguard Worker     }
95*9880d681SAndroid Build Coastguard Worker     sys::fs::remove(PrefixOutput);
96*9880d681SAndroid Build Coastguard Worker   }
97*9880d681SAndroid Build Coastguard Worker 
98*9880d681SAndroid Build Coastguard Worker   outs() << "Checking to see if these passes crash: "
99*9880d681SAndroid Build Coastguard Worker          << getPassesString(Suffix) << ": ";
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker   if (BD.runPasses(BD.getProgram(), Suffix)) {
102*9880d681SAndroid Build Coastguard Worker     delete OrigProgram;            // The suffix crashes alone...
103*9880d681SAndroid Build Coastguard Worker     return KeepSuffix;
104*9880d681SAndroid Build Coastguard Worker   }
105*9880d681SAndroid Build Coastguard Worker 
106*9880d681SAndroid Build Coastguard Worker   // Nothing failed, restore state...
107*9880d681SAndroid Build Coastguard Worker   if (OrigProgram) {
108*9880d681SAndroid Build Coastguard Worker     delete BD.Program;
109*9880d681SAndroid Build Coastguard Worker     BD.Program = OrigProgram;
110*9880d681SAndroid Build Coastguard Worker   }
111*9880d681SAndroid Build Coastguard Worker   return NoFailure;
112*9880d681SAndroid Build Coastguard Worker }
113*9880d681SAndroid Build Coastguard Worker 
114*9880d681SAndroid Build Coastguard Worker namespace {
115*9880d681SAndroid Build Coastguard Worker   /// ReduceCrashingGlobalVariables - This works by removing the global
116*9880d681SAndroid Build Coastguard Worker   /// variable's initializer and seeing if the program still crashes. If it
117*9880d681SAndroid Build Coastguard Worker   /// does, then we keep that program and try again.
118*9880d681SAndroid Build Coastguard Worker   ///
119*9880d681SAndroid Build Coastguard Worker   class ReduceCrashingGlobalVariables : public ListReducer<GlobalVariable*> {
120*9880d681SAndroid Build Coastguard Worker     BugDriver &BD;
121*9880d681SAndroid Build Coastguard Worker     bool (*TestFn)(const BugDriver &, Module *);
122*9880d681SAndroid Build Coastguard Worker   public:
ReduceCrashingGlobalVariables(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))123*9880d681SAndroid Build Coastguard Worker     ReduceCrashingGlobalVariables(BugDriver &bd,
124*9880d681SAndroid Build Coastguard Worker                                   bool (*testFn)(const BugDriver &, Module *))
125*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
126*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<GlobalVariable * > & Prefix,std::vector<GlobalVariable * > & Kept,std::string & Error)127*9880d681SAndroid Build Coastguard Worker     TestResult doTest(std::vector<GlobalVariable*> &Prefix,
128*9880d681SAndroid Build Coastguard Worker                       std::vector<GlobalVariable*> &Kept,
129*9880d681SAndroid Build Coastguard Worker                       std::string &Error) override {
130*9880d681SAndroid Build Coastguard Worker       if (!Kept.empty() && TestGlobalVariables(Kept))
131*9880d681SAndroid Build Coastguard Worker         return KeepSuffix;
132*9880d681SAndroid Build Coastguard Worker       if (!Prefix.empty() && TestGlobalVariables(Prefix))
133*9880d681SAndroid Build Coastguard Worker         return KeepPrefix;
134*9880d681SAndroid Build Coastguard Worker       return NoFailure;
135*9880d681SAndroid Build Coastguard Worker     }
136*9880d681SAndroid Build Coastguard Worker 
137*9880d681SAndroid Build Coastguard Worker     bool TestGlobalVariables(std::vector<GlobalVariable*> &GVs);
138*9880d681SAndroid Build Coastguard Worker   };
139*9880d681SAndroid Build Coastguard Worker }
140*9880d681SAndroid Build Coastguard Worker 
141*9880d681SAndroid Build Coastguard Worker bool
TestGlobalVariables(std::vector<GlobalVariable * > & GVs)142*9880d681SAndroid Build Coastguard Worker ReduceCrashingGlobalVariables::TestGlobalVariables(
143*9880d681SAndroid Build Coastguard Worker                               std::vector<GlobalVariable*> &GVs) {
144*9880d681SAndroid Build Coastguard Worker   // Clone the program to try hacking it apart...
145*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
146*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker   // Convert list to set for fast lookup...
149*9880d681SAndroid Build Coastguard Worker   std::set<GlobalVariable*> GVSet;
150*9880d681SAndroid Build Coastguard Worker 
151*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
152*9880d681SAndroid Build Coastguard Worker     GlobalVariable* CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
153*9880d681SAndroid Build Coastguard Worker     assert(CMGV && "Global Variable not in module?!");
154*9880d681SAndroid Build Coastguard Worker     GVSet.insert(CMGV);
155*9880d681SAndroid Build Coastguard Worker   }
156*9880d681SAndroid Build Coastguard Worker 
157*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only these global variables: ";
158*9880d681SAndroid Build Coastguard Worker   PrintGlobalVariableList(GVs);
159*9880d681SAndroid Build Coastguard Worker   outs() << ": ";
160*9880d681SAndroid Build Coastguard Worker 
161*9880d681SAndroid Build Coastguard Worker   // Loop over and delete any global variables which we aren't supposed to be
162*9880d681SAndroid Build Coastguard Worker   // playing with...
163*9880d681SAndroid Build Coastguard Worker   for (GlobalVariable &I : M->globals())
164*9880d681SAndroid Build Coastguard Worker     if (I.hasInitializer() && !GVSet.count(&I)) {
165*9880d681SAndroid Build Coastguard Worker       DeleteGlobalInitializer(&I);
166*9880d681SAndroid Build Coastguard Worker       I.setLinkage(GlobalValue::ExternalLinkage);
167*9880d681SAndroid Build Coastguard Worker       I.setComdat(nullptr);
168*9880d681SAndroid Build Coastguard Worker     }
169*9880d681SAndroid Build Coastguard Worker 
170*9880d681SAndroid Build Coastguard Worker   // Try running the hacked up program...
171*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
172*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M);        // It crashed, keep the trimmed version...
173*9880d681SAndroid Build Coastguard Worker 
174*9880d681SAndroid Build Coastguard Worker     // Make sure to use global variable pointers that point into the now-current
175*9880d681SAndroid Build Coastguard Worker     // module.
176*9880d681SAndroid Build Coastguard Worker     GVs.assign(GVSet.begin(), GVSet.end());
177*9880d681SAndroid Build Coastguard Worker     return true;
178*9880d681SAndroid Build Coastguard Worker   }
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker   delete M;
181*9880d681SAndroid Build Coastguard Worker   return false;
182*9880d681SAndroid Build Coastguard Worker }
183*9880d681SAndroid Build Coastguard Worker 
184*9880d681SAndroid Build Coastguard Worker namespace {
185*9880d681SAndroid Build Coastguard Worker   /// ReduceCrashingFunctions reducer - This works by removing functions and
186*9880d681SAndroid Build Coastguard Worker   /// seeing if the program still crashes. If it does, then keep the newer,
187*9880d681SAndroid Build Coastguard Worker   /// smaller program.
188*9880d681SAndroid Build Coastguard Worker   ///
189*9880d681SAndroid Build Coastguard Worker   class ReduceCrashingFunctions : public ListReducer<Function*> {
190*9880d681SAndroid Build Coastguard Worker     BugDriver &BD;
191*9880d681SAndroid Build Coastguard Worker     bool (*TestFn)(const BugDriver &, Module *);
192*9880d681SAndroid Build Coastguard Worker   public:
ReduceCrashingFunctions(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))193*9880d681SAndroid Build Coastguard Worker     ReduceCrashingFunctions(BugDriver &bd,
194*9880d681SAndroid Build Coastguard Worker                             bool (*testFn)(const BugDriver &, Module *))
195*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
196*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<Function * > & Prefix,std::vector<Function * > & Kept,std::string & Error)197*9880d681SAndroid Build Coastguard Worker     TestResult doTest(std::vector<Function*> &Prefix,
198*9880d681SAndroid Build Coastguard Worker                       std::vector<Function*> &Kept,
199*9880d681SAndroid Build Coastguard Worker                       std::string &Error) override {
200*9880d681SAndroid Build Coastguard Worker       if (!Kept.empty() && TestFuncs(Kept))
201*9880d681SAndroid Build Coastguard Worker         return KeepSuffix;
202*9880d681SAndroid Build Coastguard Worker       if (!Prefix.empty() && TestFuncs(Prefix))
203*9880d681SAndroid Build Coastguard Worker         return KeepPrefix;
204*9880d681SAndroid Build Coastguard Worker       return NoFailure;
205*9880d681SAndroid Build Coastguard Worker     }
206*9880d681SAndroid Build Coastguard Worker 
207*9880d681SAndroid Build Coastguard Worker     bool TestFuncs(std::vector<Function*> &Prefix);
208*9880d681SAndroid Build Coastguard Worker   };
209*9880d681SAndroid Build Coastguard Worker }
210*9880d681SAndroid Build Coastguard Worker 
RemoveFunctionReferences(Module * M,const char * Name)211*9880d681SAndroid Build Coastguard Worker static void RemoveFunctionReferences(Module *M, const char* Name) {
212*9880d681SAndroid Build Coastguard Worker   auto *UsedVar = M->getGlobalVariable(Name, true);
213*9880d681SAndroid Build Coastguard Worker   if (!UsedVar || !UsedVar->hasInitializer()) return;
214*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
215*9880d681SAndroid Build Coastguard Worker     assert(UsedVar->use_empty());
216*9880d681SAndroid Build Coastguard Worker     UsedVar->eraseFromParent();
217*9880d681SAndroid Build Coastguard Worker     return;
218*9880d681SAndroid Build Coastguard Worker   }
219*9880d681SAndroid Build Coastguard Worker   auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
220*9880d681SAndroid Build Coastguard Worker   std::vector<Constant*> Used;
221*9880d681SAndroid Build Coastguard Worker   for(Value *V : OldUsedVal->operand_values()) {
222*9880d681SAndroid Build Coastguard Worker     Constant *Op = cast<Constant>(V->stripPointerCasts());
223*9880d681SAndroid Build Coastguard Worker     if(!Op->isNullValue()) {
224*9880d681SAndroid Build Coastguard Worker       Used.push_back(cast<Constant>(V));
225*9880d681SAndroid Build Coastguard Worker     }
226*9880d681SAndroid Build Coastguard Worker   }
227*9880d681SAndroid Build Coastguard Worker   auto *NewValElemTy = OldUsedVal->getType()->getElementType();
228*9880d681SAndroid Build Coastguard Worker   auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
229*9880d681SAndroid Build Coastguard Worker   auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
230*9880d681SAndroid Build Coastguard Worker   UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
231*9880d681SAndroid Build Coastguard Worker   UsedVar->setInitializer(NewUsedVal);
232*9880d681SAndroid Build Coastguard Worker }
233*9880d681SAndroid Build Coastguard Worker 
TestFuncs(std::vector<Function * > & Funcs)234*9880d681SAndroid Build Coastguard Worker bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
235*9880d681SAndroid Build Coastguard Worker   // If main isn't present, claim there is no problem.
236*9880d681SAndroid Build Coastguard Worker   if (KeepMain && std::find(Funcs.begin(), Funcs.end(),
237*9880d681SAndroid Build Coastguard Worker                             BD.getProgram()->getFunction("main")) ==
238*9880d681SAndroid Build Coastguard Worker                       Funcs.end())
239*9880d681SAndroid Build Coastguard Worker     return false;
240*9880d681SAndroid Build Coastguard Worker 
241*9880d681SAndroid Build Coastguard Worker   // Clone the program to try hacking it apart...
242*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
243*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
244*9880d681SAndroid Build Coastguard Worker 
245*9880d681SAndroid Build Coastguard Worker   // Convert list to set for fast lookup...
246*9880d681SAndroid Build Coastguard Worker   std::set<Function*> Functions;
247*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
248*9880d681SAndroid Build Coastguard Worker     Function *CMF = cast<Function>(VMap[Funcs[i]]);
249*9880d681SAndroid Build Coastguard Worker     assert(CMF && "Function not in module?!");
250*9880d681SAndroid Build Coastguard Worker     assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
251*9880d681SAndroid Build Coastguard Worker     assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
252*9880d681SAndroid Build Coastguard Worker     Functions.insert(CMF);
253*9880d681SAndroid Build Coastguard Worker   }
254*9880d681SAndroid Build Coastguard Worker 
255*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only these functions: ";
256*9880d681SAndroid Build Coastguard Worker   PrintFunctionList(Funcs);
257*9880d681SAndroid Build Coastguard Worker   outs() << ": ";
258*9880d681SAndroid Build Coastguard Worker   if (!ReplaceFuncsWithNull) {
259*9880d681SAndroid Build Coastguard Worker     // Loop over and delete any functions which we aren't supposed to be playing
260*9880d681SAndroid Build Coastguard Worker     // with...
261*9880d681SAndroid Build Coastguard Worker     for (Function &I : *M)
262*9880d681SAndroid Build Coastguard Worker       if (!I.isDeclaration() && !Functions.count(&I))
263*9880d681SAndroid Build Coastguard Worker         DeleteFunctionBody(&I);
264*9880d681SAndroid Build Coastguard Worker   } else {
265*9880d681SAndroid Build Coastguard Worker     std::vector<GlobalValue*> ToRemove;
266*9880d681SAndroid Build Coastguard Worker     // First, remove aliases to functions we're about to purge.
267*9880d681SAndroid Build Coastguard Worker     for (GlobalAlias &Alias : M->aliases()) {
268*9880d681SAndroid Build Coastguard Worker       GlobalObject *Root = Alias.getBaseObject();
269*9880d681SAndroid Build Coastguard Worker       Function *F = dyn_cast_or_null<Function>(Root);
270*9880d681SAndroid Build Coastguard Worker       if (F) {
271*9880d681SAndroid Build Coastguard Worker         if (Functions.count(F))
272*9880d681SAndroid Build Coastguard Worker           // We're keeping this function.
273*9880d681SAndroid Build Coastguard Worker           continue;
274*9880d681SAndroid Build Coastguard Worker       } else if (Root->isNullValue()) {
275*9880d681SAndroid Build Coastguard Worker         // This referenced a globalalias that we've already replaced,
276*9880d681SAndroid Build Coastguard Worker         // so we still need to replace this alias.
277*9880d681SAndroid Build Coastguard Worker       } else if (!F) {
278*9880d681SAndroid Build Coastguard Worker         // Not a function, therefore not something we mess with.
279*9880d681SAndroid Build Coastguard Worker         continue;
280*9880d681SAndroid Build Coastguard Worker       }
281*9880d681SAndroid Build Coastguard Worker 
282*9880d681SAndroid Build Coastguard Worker       PointerType *Ty = cast<PointerType>(Alias.getType());
283*9880d681SAndroid Build Coastguard Worker       Constant *Replacement = ConstantPointerNull::get(Ty);
284*9880d681SAndroid Build Coastguard Worker       Alias.replaceAllUsesWith(Replacement);
285*9880d681SAndroid Build Coastguard Worker       ToRemove.push_back(&Alias);
286*9880d681SAndroid Build Coastguard Worker     }
287*9880d681SAndroid Build Coastguard Worker 
288*9880d681SAndroid Build Coastguard Worker     for (Function &I : *M) {
289*9880d681SAndroid Build Coastguard Worker       if (!I.isDeclaration() && !Functions.count(&I)) {
290*9880d681SAndroid Build Coastguard Worker         PointerType *Ty = cast<PointerType>(I.getType());
291*9880d681SAndroid Build Coastguard Worker         Constant *Replacement = ConstantPointerNull::get(Ty);
292*9880d681SAndroid Build Coastguard Worker         I.replaceAllUsesWith(Replacement);
293*9880d681SAndroid Build Coastguard Worker         ToRemove.push_back(&I);
294*9880d681SAndroid Build Coastguard Worker       }
295*9880d681SAndroid Build Coastguard Worker     }
296*9880d681SAndroid Build Coastguard Worker 
297*9880d681SAndroid Build Coastguard Worker     for (auto *F : ToRemove) {
298*9880d681SAndroid Build Coastguard Worker       F->eraseFromParent();
299*9880d681SAndroid Build Coastguard Worker     }
300*9880d681SAndroid Build Coastguard Worker 
301*9880d681SAndroid Build Coastguard Worker     // Finally, remove any null members from any global intrinsic.
302*9880d681SAndroid Build Coastguard Worker     RemoveFunctionReferences(M, "llvm.used");
303*9880d681SAndroid Build Coastguard Worker     RemoveFunctionReferences(M, "llvm.compiler.used");
304*9880d681SAndroid Build Coastguard Worker   }
305*9880d681SAndroid Build Coastguard Worker   // Try running the hacked up program...
306*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
307*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M);        // It crashed, keep the trimmed version...
308*9880d681SAndroid Build Coastguard Worker 
309*9880d681SAndroid Build Coastguard Worker     // Make sure to use function pointers that point into the now-current
310*9880d681SAndroid Build Coastguard Worker     // module.
311*9880d681SAndroid Build Coastguard Worker     Funcs.assign(Functions.begin(), Functions.end());
312*9880d681SAndroid Build Coastguard Worker     return true;
313*9880d681SAndroid Build Coastguard Worker   }
314*9880d681SAndroid Build Coastguard Worker   delete M;
315*9880d681SAndroid Build Coastguard Worker   return false;
316*9880d681SAndroid Build Coastguard Worker }
317*9880d681SAndroid Build Coastguard Worker 
318*9880d681SAndroid Build Coastguard Worker 
319*9880d681SAndroid Build Coastguard Worker namespace {
320*9880d681SAndroid Build Coastguard Worker   /// ReduceCrashingBlocks reducer - This works by setting the terminators of
321*9880d681SAndroid Build Coastguard Worker   /// all terminators except the specified basic blocks to a 'ret' instruction,
322*9880d681SAndroid Build Coastguard Worker   /// then running the simplify-cfg pass.  This has the effect of chopping up
323*9880d681SAndroid Build Coastguard Worker   /// the CFG really fast which can reduce large functions quickly.
324*9880d681SAndroid Build Coastguard Worker   ///
325*9880d681SAndroid Build Coastguard Worker   class ReduceCrashingBlocks : public ListReducer<const BasicBlock*> {
326*9880d681SAndroid Build Coastguard Worker     BugDriver &BD;
327*9880d681SAndroid Build Coastguard Worker     bool (*TestFn)(const BugDriver &, Module *);
328*9880d681SAndroid Build Coastguard Worker   public:
ReduceCrashingBlocks(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))329*9880d681SAndroid Build Coastguard Worker     ReduceCrashingBlocks(BugDriver &bd,
330*9880d681SAndroid Build Coastguard Worker                          bool (*testFn)(const BugDriver &, Module *))
331*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
332*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<const BasicBlock * > & Prefix,std::vector<const BasicBlock * > & Kept,std::string & Error)333*9880d681SAndroid Build Coastguard Worker     TestResult doTest(std::vector<const BasicBlock*> &Prefix,
334*9880d681SAndroid Build Coastguard Worker                       std::vector<const BasicBlock*> &Kept,
335*9880d681SAndroid Build Coastguard Worker                       std::string &Error) override {
336*9880d681SAndroid Build Coastguard Worker       if (!Kept.empty() && TestBlocks(Kept))
337*9880d681SAndroid Build Coastguard Worker         return KeepSuffix;
338*9880d681SAndroid Build Coastguard Worker       if (!Prefix.empty() && TestBlocks(Prefix))
339*9880d681SAndroid Build Coastguard Worker         return KeepPrefix;
340*9880d681SAndroid Build Coastguard Worker       return NoFailure;
341*9880d681SAndroid Build Coastguard Worker     }
342*9880d681SAndroid Build Coastguard Worker 
343*9880d681SAndroid Build Coastguard Worker     bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
344*9880d681SAndroid Build Coastguard Worker   };
345*9880d681SAndroid Build Coastguard Worker }
346*9880d681SAndroid Build Coastguard Worker 
TestBlocks(std::vector<const BasicBlock * > & BBs)347*9880d681SAndroid Build Coastguard Worker bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
348*9880d681SAndroid Build Coastguard Worker   // Clone the program to try hacking it apart...
349*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
350*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
351*9880d681SAndroid Build Coastguard Worker 
352*9880d681SAndroid Build Coastguard Worker   // Convert list to set for fast lookup...
353*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock*, 8> Blocks;
354*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = BBs.size(); i != e; ++i)
355*9880d681SAndroid Build Coastguard Worker     Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
356*9880d681SAndroid Build Coastguard Worker 
357*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only these blocks:";
358*9880d681SAndroid Build Coastguard Worker   unsigned NumPrint = Blocks.size();
359*9880d681SAndroid Build Coastguard Worker   if (NumPrint > 10) NumPrint = 10;
360*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = NumPrint; i != e; ++i)
361*9880d681SAndroid Build Coastguard Worker     outs() << " " << BBs[i]->getName();
362*9880d681SAndroid Build Coastguard Worker   if (NumPrint < Blocks.size())
363*9880d681SAndroid Build Coastguard Worker     outs() << "... <" << Blocks.size() << " total>";
364*9880d681SAndroid Build Coastguard Worker   outs() << ": ";
365*9880d681SAndroid Build Coastguard Worker 
366*9880d681SAndroid Build Coastguard Worker   // Loop over and delete any hack up any blocks that are not listed...
367*9880d681SAndroid Build Coastguard Worker   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
368*9880d681SAndroid Build Coastguard Worker     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
369*9880d681SAndroid Build Coastguard Worker       if (!Blocks.count(&*BB) && BB->getTerminator()->getNumSuccessors()) {
370*9880d681SAndroid Build Coastguard Worker         // Loop over all of the successors of this block, deleting any PHI nodes
371*9880d681SAndroid Build Coastguard Worker         // that might include it.
372*9880d681SAndroid Build Coastguard Worker         for (succ_iterator SI = succ_begin(&*BB), E = succ_end(&*BB); SI != E;
373*9880d681SAndroid Build Coastguard Worker              ++SI)
374*9880d681SAndroid Build Coastguard Worker           (*SI)->removePredecessor(&*BB);
375*9880d681SAndroid Build Coastguard Worker 
376*9880d681SAndroid Build Coastguard Worker         TerminatorInst *BBTerm = BB->getTerminator();
377*9880d681SAndroid Build Coastguard Worker         if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
378*9880d681SAndroid Build Coastguard Worker           continue;
379*9880d681SAndroid Build Coastguard Worker         if (!BBTerm->getType()->isVoidTy())
380*9880d681SAndroid Build Coastguard Worker           BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
381*9880d681SAndroid Build Coastguard Worker 
382*9880d681SAndroid Build Coastguard Worker         // Replace the old terminator instruction.
383*9880d681SAndroid Build Coastguard Worker         BB->getInstList().pop_back();
384*9880d681SAndroid Build Coastguard Worker         new UnreachableInst(BB->getContext(), &*BB);
385*9880d681SAndroid Build Coastguard Worker       }
386*9880d681SAndroid Build Coastguard Worker 
387*9880d681SAndroid Build Coastguard Worker   // The CFG Simplifier pass may delete one of the basic blocks we are
388*9880d681SAndroid Build Coastguard Worker   // interested in.  If it does we need to take the block out of the list.  Make
389*9880d681SAndroid Build Coastguard Worker   // a "persistent mapping" by turning basic blocks into <function, name> pairs.
390*9880d681SAndroid Build Coastguard Worker   // This won't work well if blocks are unnamed, but that is just the risk we
391*9880d681SAndroid Build Coastguard Worker   // have to take.
392*9880d681SAndroid Build Coastguard Worker   std::vector<std::pair<std::string, std::string> > BlockInfo;
393*9880d681SAndroid Build Coastguard Worker 
394*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *BB : Blocks)
395*9880d681SAndroid Build Coastguard Worker     BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
396*9880d681SAndroid Build Coastguard Worker 
397*9880d681SAndroid Build Coastguard Worker   // Now run the CFG simplify pass on the function...
398*9880d681SAndroid Build Coastguard Worker   std::vector<std::string> Passes;
399*9880d681SAndroid Build Coastguard Worker   Passes.push_back("simplifycfg");
400*9880d681SAndroid Build Coastguard Worker   Passes.push_back("verify");
401*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<Module> New = BD.runPassesOn(M, Passes);
402*9880d681SAndroid Build Coastguard Worker   delete M;
403*9880d681SAndroid Build Coastguard Worker   if (!New) {
404*9880d681SAndroid Build Coastguard Worker     errs() << "simplifycfg failed!\n";
405*9880d681SAndroid Build Coastguard Worker     exit(1);
406*9880d681SAndroid Build Coastguard Worker   }
407*9880d681SAndroid Build Coastguard Worker   M = New.release();
408*9880d681SAndroid Build Coastguard Worker 
409*9880d681SAndroid Build Coastguard Worker   // Try running on the hacked up program...
410*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
411*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M);      // It crashed, keep the trimmed version...
412*9880d681SAndroid Build Coastguard Worker 
413*9880d681SAndroid Build Coastguard Worker     // Make sure to use basic block pointers that point into the now-current
414*9880d681SAndroid Build Coastguard Worker     // module, and that they don't include any deleted blocks.
415*9880d681SAndroid Build Coastguard Worker     BBs.clear();
416*9880d681SAndroid Build Coastguard Worker     const ValueSymbolTable &GST = M->getValueSymbolTable();
417*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
418*9880d681SAndroid Build Coastguard Worker       Function *F = cast<Function>(GST.lookup(BlockInfo[i].first));
419*9880d681SAndroid Build Coastguard Worker       ValueSymbolTable &ST = F->getValueSymbolTable();
420*9880d681SAndroid Build Coastguard Worker       Value* V = ST.lookup(BlockInfo[i].second);
421*9880d681SAndroid Build Coastguard Worker       if (V && V->getType() == Type::getLabelTy(V->getContext()))
422*9880d681SAndroid Build Coastguard Worker         BBs.push_back(cast<BasicBlock>(V));
423*9880d681SAndroid Build Coastguard Worker     }
424*9880d681SAndroid Build Coastguard Worker     return true;
425*9880d681SAndroid Build Coastguard Worker   }
426*9880d681SAndroid Build Coastguard Worker   delete M;  // It didn't crash, try something else.
427*9880d681SAndroid Build Coastguard Worker   return false;
428*9880d681SAndroid Build Coastguard Worker }
429*9880d681SAndroid Build Coastguard Worker 
430*9880d681SAndroid Build Coastguard Worker namespace {
431*9880d681SAndroid Build Coastguard Worker   /// ReduceCrashingInstructions reducer - This works by removing the specified
432*9880d681SAndroid Build Coastguard Worker   /// non-terminator instructions and replacing them with undef.
433*9880d681SAndroid Build Coastguard Worker   ///
434*9880d681SAndroid Build Coastguard Worker   class ReduceCrashingInstructions : public ListReducer<const Instruction*> {
435*9880d681SAndroid Build Coastguard Worker     BugDriver &BD;
436*9880d681SAndroid Build Coastguard Worker     bool (*TestFn)(const BugDriver &, Module *);
437*9880d681SAndroid Build Coastguard Worker   public:
ReduceCrashingInstructions(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))438*9880d681SAndroid Build Coastguard Worker     ReduceCrashingInstructions(BugDriver &bd,
439*9880d681SAndroid Build Coastguard Worker                                bool (*testFn)(const BugDriver &, Module *))
440*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
441*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<const Instruction * > & Prefix,std::vector<const Instruction * > & Kept,std::string & Error)442*9880d681SAndroid Build Coastguard Worker     TestResult doTest(std::vector<const Instruction*> &Prefix,
443*9880d681SAndroid Build Coastguard Worker                       std::vector<const Instruction*> &Kept,
444*9880d681SAndroid Build Coastguard Worker                       std::string &Error) override {
445*9880d681SAndroid Build Coastguard Worker       if (!Kept.empty() && TestInsts(Kept))
446*9880d681SAndroid Build Coastguard Worker         return KeepSuffix;
447*9880d681SAndroid Build Coastguard Worker       if (!Prefix.empty() && TestInsts(Prefix))
448*9880d681SAndroid Build Coastguard Worker         return KeepPrefix;
449*9880d681SAndroid Build Coastguard Worker       return NoFailure;
450*9880d681SAndroid Build Coastguard Worker     }
451*9880d681SAndroid Build Coastguard Worker 
452*9880d681SAndroid Build Coastguard Worker     bool TestInsts(std::vector<const Instruction*> &Prefix);
453*9880d681SAndroid Build Coastguard Worker   };
454*9880d681SAndroid Build Coastguard Worker }
455*9880d681SAndroid Build Coastguard Worker 
TestInsts(std::vector<const Instruction * > & Insts)456*9880d681SAndroid Build Coastguard Worker bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
457*9880d681SAndroid Build Coastguard Worker                                            &Insts) {
458*9880d681SAndroid Build Coastguard Worker   // Clone the program to try hacking it apart...
459*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
460*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
461*9880d681SAndroid Build Coastguard Worker 
462*9880d681SAndroid Build Coastguard Worker   // Convert list to set for fast lookup...
463*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Instruction*, 32> Instructions;
464*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
465*9880d681SAndroid Build Coastguard Worker     assert(!isa<TerminatorInst>(Insts[i]));
466*9880d681SAndroid Build Coastguard Worker     Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
467*9880d681SAndroid Build Coastguard Worker   }
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only " << Instructions.size();
470*9880d681SAndroid Build Coastguard Worker   if (Instructions.size() == 1)
471*9880d681SAndroid Build Coastguard Worker     outs() << " instruction: ";
472*9880d681SAndroid Build Coastguard Worker   else
473*9880d681SAndroid Build Coastguard Worker     outs() << " instructions: ";
474*9880d681SAndroid Build Coastguard Worker 
475*9880d681SAndroid Build Coastguard Worker   for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
476*9880d681SAndroid Build Coastguard Worker     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
477*9880d681SAndroid Build Coastguard Worker       for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
478*9880d681SAndroid Build Coastguard Worker         Instruction *Inst = &*I++;
479*9880d681SAndroid Build Coastguard Worker         if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
480*9880d681SAndroid Build Coastguard Worker             !Inst->isEHPad() && !Inst->getType()->isTokenTy()) {
481*9880d681SAndroid Build Coastguard Worker           if (!Inst->getType()->isVoidTy())
482*9880d681SAndroid Build Coastguard Worker             Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
483*9880d681SAndroid Build Coastguard Worker           Inst->eraseFromParent();
484*9880d681SAndroid Build Coastguard Worker         }
485*9880d681SAndroid Build Coastguard Worker       }
486*9880d681SAndroid Build Coastguard Worker 
487*9880d681SAndroid Build Coastguard Worker   // Verify that this is still valid.
488*9880d681SAndroid Build Coastguard Worker   legacy::PassManager Passes;
489*9880d681SAndroid Build Coastguard Worker   Passes.add(createVerifierPass());
490*9880d681SAndroid Build Coastguard Worker   Passes.run(*M);
491*9880d681SAndroid Build Coastguard Worker 
492*9880d681SAndroid Build Coastguard Worker   // Try running on the hacked up program...
493*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
494*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M);      // It crashed, keep the trimmed version...
495*9880d681SAndroid Build Coastguard Worker 
496*9880d681SAndroid Build Coastguard Worker     // Make sure to use instruction pointers that point into the now-current
497*9880d681SAndroid Build Coastguard Worker     // module, and that they don't include any deleted blocks.
498*9880d681SAndroid Build Coastguard Worker     Insts.clear();
499*9880d681SAndroid Build Coastguard Worker     for (Instruction *Inst : Instructions)
500*9880d681SAndroid Build Coastguard Worker       Insts.push_back(Inst);
501*9880d681SAndroid Build Coastguard Worker     return true;
502*9880d681SAndroid Build Coastguard Worker   }
503*9880d681SAndroid Build Coastguard Worker   delete M;  // It didn't crash, try something else.
504*9880d681SAndroid Build Coastguard Worker   return false;
505*9880d681SAndroid Build Coastguard Worker }
506*9880d681SAndroid Build Coastguard Worker 
507*9880d681SAndroid Build Coastguard Worker namespace {
508*9880d681SAndroid Build Coastguard Worker // Reduce the list of Named Metadata nodes. We keep this as a list of
509*9880d681SAndroid Build Coastguard Worker // names to avoid having to convert back and forth every time.
510*9880d681SAndroid Build Coastguard Worker class ReduceCrashingNamedMD : public ListReducer<std::string> {
511*9880d681SAndroid Build Coastguard Worker   BugDriver &BD;
512*9880d681SAndroid Build Coastguard Worker   bool (*TestFn)(const BugDriver &, Module *);
513*9880d681SAndroid Build Coastguard Worker 
514*9880d681SAndroid Build Coastguard Worker public:
ReduceCrashingNamedMD(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))515*9880d681SAndroid Build Coastguard Worker   ReduceCrashingNamedMD(BugDriver &bd,
516*9880d681SAndroid Build Coastguard Worker                         bool (*testFn)(const BugDriver &, Module *))
517*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
518*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Kept,std::string & Error)519*9880d681SAndroid Build Coastguard Worker   TestResult doTest(std::vector<std::string> &Prefix,
520*9880d681SAndroid Build Coastguard Worker                     std::vector<std::string> &Kept,
521*9880d681SAndroid Build Coastguard Worker                     std::string &Error) override {
522*9880d681SAndroid Build Coastguard Worker     if (!Kept.empty() && TestNamedMDs(Kept))
523*9880d681SAndroid Build Coastguard Worker       return KeepSuffix;
524*9880d681SAndroid Build Coastguard Worker     if (!Prefix.empty() && TestNamedMDs(Prefix))
525*9880d681SAndroid Build Coastguard Worker       return KeepPrefix;
526*9880d681SAndroid Build Coastguard Worker     return NoFailure;
527*9880d681SAndroid Build Coastguard Worker   }
528*9880d681SAndroid Build Coastguard Worker 
529*9880d681SAndroid Build Coastguard Worker   bool TestNamedMDs(std::vector<std::string> &NamedMDs);
530*9880d681SAndroid Build Coastguard Worker };
531*9880d681SAndroid Build Coastguard Worker }
532*9880d681SAndroid Build Coastguard Worker 
TestNamedMDs(std::vector<std::string> & NamedMDs)533*9880d681SAndroid Build Coastguard Worker bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
534*9880d681SAndroid Build Coastguard Worker 
535*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
536*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
537*9880d681SAndroid Build Coastguard Worker 
538*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only these named metadata nodes:";
539*9880d681SAndroid Build Coastguard Worker   unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
540*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = NumPrint; i != e; ++i)
541*9880d681SAndroid Build Coastguard Worker     outs() << " " << NamedMDs[i];
542*9880d681SAndroid Build Coastguard Worker   if (NumPrint < NamedMDs.size())
543*9880d681SAndroid Build Coastguard Worker     outs() << "... <" << NamedMDs.size() << " total>";
544*9880d681SAndroid Build Coastguard Worker   outs() << ": ";
545*9880d681SAndroid Build Coastguard Worker 
546*9880d681SAndroid Build Coastguard Worker   // Make a StringMap for faster lookup
547*9880d681SAndroid Build Coastguard Worker   StringSet<> Names;
548*9880d681SAndroid Build Coastguard Worker   for (const std::string &Name : NamedMDs)
549*9880d681SAndroid Build Coastguard Worker     Names.insert(Name);
550*9880d681SAndroid Build Coastguard Worker 
551*9880d681SAndroid Build Coastguard Worker   // First collect all the metadata to delete in a vector, then
552*9880d681SAndroid Build Coastguard Worker   // delete them all at once to avoid invalidating the iterator
553*9880d681SAndroid Build Coastguard Worker   std::vector<NamedMDNode *> ToDelete;
554*9880d681SAndroid Build Coastguard Worker   ToDelete.reserve(M->named_metadata_size() - Names.size());
555*9880d681SAndroid Build Coastguard Worker   for (auto &NamedMD : M->named_metadata())
556*9880d681SAndroid Build Coastguard Worker     // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
557*9880d681SAndroid Build Coastguard Worker     if (!Names.count(NamedMD.getName()) &&
558*9880d681SAndroid Build Coastguard Worker         (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
559*9880d681SAndroid Build Coastguard Worker       ToDelete.push_back(&NamedMD);
560*9880d681SAndroid Build Coastguard Worker 
561*9880d681SAndroid Build Coastguard Worker   for (auto *NamedMD : ToDelete)
562*9880d681SAndroid Build Coastguard Worker     NamedMD->eraseFromParent();
563*9880d681SAndroid Build Coastguard Worker 
564*9880d681SAndroid Build Coastguard Worker   // Verify that this is still valid.
565*9880d681SAndroid Build Coastguard Worker   legacy::PassManager Passes;
566*9880d681SAndroid Build Coastguard Worker   Passes.add(createVerifierPass());
567*9880d681SAndroid Build Coastguard Worker   Passes.run(*M);
568*9880d681SAndroid Build Coastguard Worker 
569*9880d681SAndroid Build Coastguard Worker   // Try running on the hacked up program...
570*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
571*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M); // It crashed, keep the trimmed version...
572*9880d681SAndroid Build Coastguard Worker     return true;
573*9880d681SAndroid Build Coastguard Worker   }
574*9880d681SAndroid Build Coastguard Worker   delete M; // It didn't crash, try something else.
575*9880d681SAndroid Build Coastguard Worker   return false;
576*9880d681SAndroid Build Coastguard Worker }
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker namespace {
579*9880d681SAndroid Build Coastguard Worker // Reduce the list of operands to named metadata nodes
580*9880d681SAndroid Build Coastguard Worker class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
581*9880d681SAndroid Build Coastguard Worker   BugDriver &BD;
582*9880d681SAndroid Build Coastguard Worker   bool (*TestFn)(const BugDriver &, Module *);
583*9880d681SAndroid Build Coastguard Worker 
584*9880d681SAndroid Build Coastguard Worker public:
ReduceCrashingNamedMDOps(BugDriver & bd,bool (* testFn)(const BugDriver &,Module *))585*9880d681SAndroid Build Coastguard Worker   ReduceCrashingNamedMDOps(BugDriver &bd,
586*9880d681SAndroid Build Coastguard Worker                            bool (*testFn)(const BugDriver &, Module *))
587*9880d681SAndroid Build Coastguard Worker       : BD(bd), TestFn(testFn) {}
588*9880d681SAndroid Build Coastguard Worker 
doTest(std::vector<const MDNode * > & Prefix,std::vector<const MDNode * > & Kept,std::string & Error)589*9880d681SAndroid Build Coastguard Worker   TestResult doTest(std::vector<const MDNode *> &Prefix,
590*9880d681SAndroid Build Coastguard Worker                     std::vector<const MDNode *> &Kept,
591*9880d681SAndroid Build Coastguard Worker                     std::string &Error) override {
592*9880d681SAndroid Build Coastguard Worker     if (!Kept.empty() && TestNamedMDOps(Kept))
593*9880d681SAndroid Build Coastguard Worker       return KeepSuffix;
594*9880d681SAndroid Build Coastguard Worker     if (!Prefix.empty() && TestNamedMDOps(Prefix))
595*9880d681SAndroid Build Coastguard Worker       return KeepPrefix;
596*9880d681SAndroid Build Coastguard Worker     return NoFailure;
597*9880d681SAndroid Build Coastguard Worker   }
598*9880d681SAndroid Build Coastguard Worker 
599*9880d681SAndroid Build Coastguard Worker   bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
600*9880d681SAndroid Build Coastguard Worker };
601*9880d681SAndroid Build Coastguard Worker }
602*9880d681SAndroid Build Coastguard Worker 
TestNamedMDOps(std::vector<const MDNode * > & NamedMDOps)603*9880d681SAndroid Build Coastguard Worker bool ReduceCrashingNamedMDOps::TestNamedMDOps(
604*9880d681SAndroid Build Coastguard Worker     std::vector<const MDNode *> &NamedMDOps) {
605*9880d681SAndroid Build Coastguard Worker   // Convert list to set for fast lookup...
606*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
607*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
608*9880d681SAndroid Build Coastguard Worker     OldMDNodeOps.insert(NamedMDOps[i]);
609*9880d681SAndroid Build Coastguard Worker   }
610*9880d681SAndroid Build Coastguard Worker 
611*9880d681SAndroid Build Coastguard Worker   outs() << "Checking for crash with only " << OldMDNodeOps.size();
612*9880d681SAndroid Build Coastguard Worker   if (OldMDNodeOps.size() == 1)
613*9880d681SAndroid Build Coastguard Worker     outs() << " named metadata operand: ";
614*9880d681SAndroid Build Coastguard Worker   else
615*9880d681SAndroid Build Coastguard Worker     outs() << " named metadata operands: ";
616*9880d681SAndroid Build Coastguard Worker 
617*9880d681SAndroid Build Coastguard Worker   ValueToValueMapTy VMap;
618*9880d681SAndroid Build Coastguard Worker   Module *M = CloneModule(BD.getProgram(), VMap).release();
619*9880d681SAndroid Build Coastguard Worker 
620*9880d681SAndroid Build Coastguard Worker   // This is a little wasteful. In the future it might be good if we could have
621*9880d681SAndroid Build Coastguard Worker   // these dropped during cloning.
622*9880d681SAndroid Build Coastguard Worker   for (auto &NamedMD : BD.getProgram()->named_metadata()) {
623*9880d681SAndroid Build Coastguard Worker     // Drop the old one and create a new one
624*9880d681SAndroid Build Coastguard Worker     M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
625*9880d681SAndroid Build Coastguard Worker     NamedMDNode *NewNamedMDNode =
626*9880d681SAndroid Build Coastguard Worker         M->getOrInsertNamedMetadata(NamedMD.getName());
627*9880d681SAndroid Build Coastguard Worker     for (MDNode *op : NamedMD.operands())
628*9880d681SAndroid Build Coastguard Worker       if (OldMDNodeOps.count(op))
629*9880d681SAndroid Build Coastguard Worker         NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
630*9880d681SAndroid Build Coastguard Worker   }
631*9880d681SAndroid Build Coastguard Worker 
632*9880d681SAndroid Build Coastguard Worker   // Verify that this is still valid.
633*9880d681SAndroid Build Coastguard Worker   legacy::PassManager Passes;
634*9880d681SAndroid Build Coastguard Worker   Passes.add(createVerifierPass());
635*9880d681SAndroid Build Coastguard Worker   Passes.run(*M);
636*9880d681SAndroid Build Coastguard Worker 
637*9880d681SAndroid Build Coastguard Worker   // Try running on the hacked up program...
638*9880d681SAndroid Build Coastguard Worker   if (TestFn(BD, M)) {
639*9880d681SAndroid Build Coastguard Worker     // Make sure to use instruction pointers that point into the now-current
640*9880d681SAndroid Build Coastguard Worker     // module, and that they don't include any deleted blocks.
641*9880d681SAndroid Build Coastguard Worker     NamedMDOps.clear();
642*9880d681SAndroid Build Coastguard Worker     for (const MDNode *Node : OldMDNodeOps)
643*9880d681SAndroid Build Coastguard Worker       NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
644*9880d681SAndroid Build Coastguard Worker 
645*9880d681SAndroid Build Coastguard Worker     BD.setNewProgram(M); // It crashed, keep the trimmed version...
646*9880d681SAndroid Build Coastguard Worker     return true;
647*9880d681SAndroid Build Coastguard Worker   }
648*9880d681SAndroid Build Coastguard Worker   delete M; // It didn't crash, try something else.
649*9880d681SAndroid Build Coastguard Worker   return false;
650*9880d681SAndroid Build Coastguard Worker }
651*9880d681SAndroid Build Coastguard Worker 
ReduceGlobalInitializers(BugDriver & BD,bool (* TestFn)(const BugDriver &,Module *),std::string & Error)652*9880d681SAndroid Build Coastguard Worker static void ReduceGlobalInitializers(BugDriver &BD,
653*9880d681SAndroid Build Coastguard Worker                                      bool (*TestFn)(const BugDriver &, Module *),
654*9880d681SAndroid Build Coastguard Worker                                      std::string &Error) {
655*9880d681SAndroid Build Coastguard Worker   if (BD.getProgram()->global_begin() != BD.getProgram()->global_end()) {
656*9880d681SAndroid Build Coastguard Worker     // Now try to reduce the number of global variable initializers in the
657*9880d681SAndroid Build Coastguard Worker     // module to something small.
658*9880d681SAndroid Build Coastguard Worker     Module *M = CloneModule(BD.getProgram()).release();
659*9880d681SAndroid Build Coastguard Worker     bool DeletedInit = false;
660*9880d681SAndroid Build Coastguard Worker 
661*9880d681SAndroid Build Coastguard Worker     for (Module::global_iterator I = M->global_begin(), E = M->global_end();
662*9880d681SAndroid Build Coastguard Worker          I != E; ++I)
663*9880d681SAndroid Build Coastguard Worker       if (I->hasInitializer()) {
664*9880d681SAndroid Build Coastguard Worker         DeleteGlobalInitializer(&*I);
665*9880d681SAndroid Build Coastguard Worker         I->setLinkage(GlobalValue::ExternalLinkage);
666*9880d681SAndroid Build Coastguard Worker         I->setComdat(nullptr);
667*9880d681SAndroid Build Coastguard Worker         DeletedInit = true;
668*9880d681SAndroid Build Coastguard Worker       }
669*9880d681SAndroid Build Coastguard Worker 
670*9880d681SAndroid Build Coastguard Worker     if (!DeletedInit) {
671*9880d681SAndroid Build Coastguard Worker       delete M;  // No change made...
672*9880d681SAndroid Build Coastguard Worker     } else {
673*9880d681SAndroid Build Coastguard Worker       // See if the program still causes a crash...
674*9880d681SAndroid Build Coastguard Worker       outs() << "\nChecking to see if we can delete global inits: ";
675*9880d681SAndroid Build Coastguard Worker 
676*9880d681SAndroid Build Coastguard Worker       if (TestFn(BD, M)) {      // Still crashes?
677*9880d681SAndroid Build Coastguard Worker         BD.setNewProgram(M);
678*9880d681SAndroid Build Coastguard Worker         outs() << "\n*** Able to remove all global initializers!\n";
679*9880d681SAndroid Build Coastguard Worker       } else {                  // No longer crashes?
680*9880d681SAndroid Build Coastguard Worker         outs() << "  - Removing all global inits hides problem!\n";
681*9880d681SAndroid Build Coastguard Worker         delete M;
682*9880d681SAndroid Build Coastguard Worker 
683*9880d681SAndroid Build Coastguard Worker         std::vector<GlobalVariable*> GVs;
684*9880d681SAndroid Build Coastguard Worker 
685*9880d681SAndroid Build Coastguard Worker         for (Module::global_iterator I = BD.getProgram()->global_begin(),
686*9880d681SAndroid Build Coastguard Worker                E = BD.getProgram()->global_end(); I != E; ++I)
687*9880d681SAndroid Build Coastguard Worker           if (I->hasInitializer())
688*9880d681SAndroid Build Coastguard Worker             GVs.push_back(&*I);
689*9880d681SAndroid Build Coastguard Worker 
690*9880d681SAndroid Build Coastguard Worker         if (GVs.size() > 1 && !BugpointIsInterrupted) {
691*9880d681SAndroid Build Coastguard Worker           outs() << "\n*** Attempting to reduce the number of global "
692*9880d681SAndroid Build Coastguard Worker                     << "variables in the testcase\n";
693*9880d681SAndroid Build Coastguard Worker 
694*9880d681SAndroid Build Coastguard Worker           unsigned OldSize = GVs.size();
695*9880d681SAndroid Build Coastguard Worker           ReduceCrashingGlobalVariables(BD, TestFn).reduceList(GVs, Error);
696*9880d681SAndroid Build Coastguard Worker           assert(!Error.empty());
697*9880d681SAndroid Build Coastguard Worker 
698*9880d681SAndroid Build Coastguard Worker           if (GVs.size() < OldSize)
699*9880d681SAndroid Build Coastguard Worker             BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
700*9880d681SAndroid Build Coastguard Worker         }
701*9880d681SAndroid Build Coastguard Worker       }
702*9880d681SAndroid Build Coastguard Worker     }
703*9880d681SAndroid Build Coastguard Worker   }
704*9880d681SAndroid Build Coastguard Worker }
705*9880d681SAndroid Build Coastguard Worker 
ReduceInsts(BugDriver & BD,bool (* TestFn)(const BugDriver &,Module *),std::string & Error)706*9880d681SAndroid Build Coastguard Worker static void ReduceInsts(BugDriver &BD,
707*9880d681SAndroid Build Coastguard Worker                         bool (*TestFn)(const BugDriver &, Module *),
708*9880d681SAndroid Build Coastguard Worker                         std::string &Error) {
709*9880d681SAndroid Build Coastguard Worker   // Attempt to delete instructions using bisection. This should help out nasty
710*9880d681SAndroid Build Coastguard Worker   // cases with large basic blocks where the problem is at one end.
711*9880d681SAndroid Build Coastguard Worker   if (!BugpointIsInterrupted) {
712*9880d681SAndroid Build Coastguard Worker     std::vector<const Instruction*> Insts;
713*9880d681SAndroid Build Coastguard Worker     for (const Function &F : *BD.getProgram())
714*9880d681SAndroid Build Coastguard Worker       for (const BasicBlock &BB : F)
715*9880d681SAndroid Build Coastguard Worker         for (const Instruction &I : BB)
716*9880d681SAndroid Build Coastguard Worker           if (!isa<TerminatorInst>(&I))
717*9880d681SAndroid Build Coastguard Worker             Insts.push_back(&I);
718*9880d681SAndroid Build Coastguard Worker 
719*9880d681SAndroid Build Coastguard Worker     ReduceCrashingInstructions(BD, TestFn).reduceList(Insts, Error);
720*9880d681SAndroid Build Coastguard Worker   }
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker   unsigned Simplification = 2;
723*9880d681SAndroid Build Coastguard Worker   do {
724*9880d681SAndroid Build Coastguard Worker     if (BugpointIsInterrupted)
725*9880d681SAndroid Build Coastguard Worker       return;
726*9880d681SAndroid Build Coastguard Worker     --Simplification;
727*9880d681SAndroid Build Coastguard Worker     outs() << "\n*** Attempting to reduce testcase by deleting instruc"
728*9880d681SAndroid Build Coastguard Worker            << "tions: Simplification Level #" << Simplification << '\n';
729*9880d681SAndroid Build Coastguard Worker 
730*9880d681SAndroid Build Coastguard Worker     // Now that we have deleted the functions that are unnecessary for the
731*9880d681SAndroid Build Coastguard Worker     // program, try to remove instructions that are not necessary to cause the
732*9880d681SAndroid Build Coastguard Worker     // crash.  To do this, we loop through all of the instructions in the
733*9880d681SAndroid Build Coastguard Worker     // remaining functions, deleting them (replacing any values produced with
734*9880d681SAndroid Build Coastguard Worker     // nulls), and then running ADCE and SimplifyCFG.  If the transformed input
735*9880d681SAndroid Build Coastguard Worker     // still triggers failure, keep deleting until we cannot trigger failure
736*9880d681SAndroid Build Coastguard Worker     // anymore.
737*9880d681SAndroid Build Coastguard Worker     //
738*9880d681SAndroid Build Coastguard Worker     unsigned InstructionsToSkipBeforeDeleting = 0;
739*9880d681SAndroid Build Coastguard Worker   TryAgain:
740*9880d681SAndroid Build Coastguard Worker 
741*9880d681SAndroid Build Coastguard Worker     // Loop over all of the (non-terminator) instructions remaining in the
742*9880d681SAndroid Build Coastguard Worker     // function, attempting to delete them.
743*9880d681SAndroid Build Coastguard Worker     unsigned CurInstructionNum = 0;
744*9880d681SAndroid Build Coastguard Worker     for (Module::const_iterator FI = BD.getProgram()->begin(),
745*9880d681SAndroid Build Coastguard Worker            E = BD.getProgram()->end(); FI != E; ++FI)
746*9880d681SAndroid Build Coastguard Worker       if (!FI->isDeclaration())
747*9880d681SAndroid Build Coastguard Worker         for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
748*9880d681SAndroid Build Coastguard Worker              ++BI)
749*9880d681SAndroid Build Coastguard Worker           for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
750*9880d681SAndroid Build Coastguard Worker                I != E; ++I, ++CurInstructionNum) {
751*9880d681SAndroid Build Coastguard Worker             if (InstructionsToSkipBeforeDeleting) {
752*9880d681SAndroid Build Coastguard Worker               --InstructionsToSkipBeforeDeleting;
753*9880d681SAndroid Build Coastguard Worker             } else {
754*9880d681SAndroid Build Coastguard Worker               if (BugpointIsInterrupted)
755*9880d681SAndroid Build Coastguard Worker                 return;
756*9880d681SAndroid Build Coastguard Worker 
757*9880d681SAndroid Build Coastguard Worker               if (I->isEHPad() || I->getType()->isTokenTy())
758*9880d681SAndroid Build Coastguard Worker                 continue;
759*9880d681SAndroid Build Coastguard Worker 
760*9880d681SAndroid Build Coastguard Worker               outs() << "Checking instruction: " << *I;
761*9880d681SAndroid Build Coastguard Worker               std::unique_ptr<Module> M =
762*9880d681SAndroid Build Coastguard Worker                   BD.deleteInstructionFromProgram(&*I, Simplification);
763*9880d681SAndroid Build Coastguard Worker 
764*9880d681SAndroid Build Coastguard Worker               // Find out if the pass still crashes on this pass...
765*9880d681SAndroid Build Coastguard Worker               if (TestFn(BD, M.get())) {
766*9880d681SAndroid Build Coastguard Worker                 // Yup, it does, we delete the old module, and continue trying
767*9880d681SAndroid Build Coastguard Worker                 // to reduce the testcase...
768*9880d681SAndroid Build Coastguard Worker                 BD.setNewProgram(M.release());
769*9880d681SAndroid Build Coastguard Worker                 InstructionsToSkipBeforeDeleting = CurInstructionNum;
770*9880d681SAndroid Build Coastguard Worker                 goto TryAgain;  // I wish I had a multi-level break here!
771*9880d681SAndroid Build Coastguard Worker               }
772*9880d681SAndroid Build Coastguard Worker             }
773*9880d681SAndroid Build Coastguard Worker           }
774*9880d681SAndroid Build Coastguard Worker 
775*9880d681SAndroid Build Coastguard Worker     if (InstructionsToSkipBeforeDeleting) {
776*9880d681SAndroid Build Coastguard Worker       InstructionsToSkipBeforeDeleting = 0;
777*9880d681SAndroid Build Coastguard Worker       goto TryAgain;
778*9880d681SAndroid Build Coastguard Worker     }
779*9880d681SAndroid Build Coastguard Worker 
780*9880d681SAndroid Build Coastguard Worker   } while (Simplification);
781*9880d681SAndroid Build Coastguard Worker   BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
782*9880d681SAndroid Build Coastguard Worker }
783*9880d681SAndroid Build Coastguard Worker 
784*9880d681SAndroid Build Coastguard Worker 
785*9880d681SAndroid Build Coastguard Worker /// DebugACrash - Given a predicate that determines whether a component crashes
786*9880d681SAndroid Build Coastguard Worker /// on a program, try to destructively reduce the program while still keeping
787*9880d681SAndroid Build Coastguard Worker /// the predicate true.
DebugACrash(BugDriver & BD,bool (* TestFn)(const BugDriver &,Module *),std::string & Error)788*9880d681SAndroid Build Coastguard Worker static bool DebugACrash(BugDriver &BD,
789*9880d681SAndroid Build Coastguard Worker                         bool (*TestFn)(const BugDriver &, Module *),
790*9880d681SAndroid Build Coastguard Worker                         std::string &Error) {
791*9880d681SAndroid Build Coastguard Worker   // See if we can get away with nuking some of the global variable initializers
792*9880d681SAndroid Build Coastguard Worker   // in the program...
793*9880d681SAndroid Build Coastguard Worker   if (!NoGlobalRM)
794*9880d681SAndroid Build Coastguard Worker     ReduceGlobalInitializers(BD, TestFn, Error);
795*9880d681SAndroid Build Coastguard Worker 
796*9880d681SAndroid Build Coastguard Worker   // Now try to reduce the number of functions in the module to something small.
797*9880d681SAndroid Build Coastguard Worker   std::vector<Function*> Functions;
798*9880d681SAndroid Build Coastguard Worker   for (Function &F : *BD.getProgram())
799*9880d681SAndroid Build Coastguard Worker     if (!F.isDeclaration())
800*9880d681SAndroid Build Coastguard Worker       Functions.push_back(&F);
801*9880d681SAndroid Build Coastguard Worker 
802*9880d681SAndroid Build Coastguard Worker   if (Functions.size() > 1 && !BugpointIsInterrupted) {
803*9880d681SAndroid Build Coastguard Worker     outs() << "\n*** Attempting to reduce the number of functions "
804*9880d681SAndroid Build Coastguard Worker       "in the testcase\n";
805*9880d681SAndroid Build Coastguard Worker 
806*9880d681SAndroid Build Coastguard Worker     unsigned OldSize = Functions.size();
807*9880d681SAndroid Build Coastguard Worker     ReduceCrashingFunctions(BD, TestFn).reduceList(Functions, Error);
808*9880d681SAndroid Build Coastguard Worker 
809*9880d681SAndroid Build Coastguard Worker     if (Functions.size() < OldSize)
810*9880d681SAndroid Build Coastguard Worker       BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
811*9880d681SAndroid Build Coastguard Worker   }
812*9880d681SAndroid Build Coastguard Worker 
813*9880d681SAndroid Build Coastguard Worker   // Attempt to delete entire basic blocks at a time to speed up
814*9880d681SAndroid Build Coastguard Worker   // convergence... this actually works by setting the terminator of the blocks
815*9880d681SAndroid Build Coastguard Worker   // to a return instruction then running simplifycfg, which can potentially
816*9880d681SAndroid Build Coastguard Worker   // shrinks the code dramatically quickly
817*9880d681SAndroid Build Coastguard Worker   //
818*9880d681SAndroid Build Coastguard Worker   if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
819*9880d681SAndroid Build Coastguard Worker     std::vector<const BasicBlock*> Blocks;
820*9880d681SAndroid Build Coastguard Worker     for (Function &F : *BD.getProgram())
821*9880d681SAndroid Build Coastguard Worker       for (BasicBlock &BB : F)
822*9880d681SAndroid Build Coastguard Worker         Blocks.push_back(&BB);
823*9880d681SAndroid Build Coastguard Worker     unsigned OldSize = Blocks.size();
824*9880d681SAndroid Build Coastguard Worker     ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks, Error);
825*9880d681SAndroid Build Coastguard Worker     if (Blocks.size() < OldSize)
826*9880d681SAndroid Build Coastguard Worker       BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
827*9880d681SAndroid Build Coastguard Worker   }
828*9880d681SAndroid Build Coastguard Worker 
829*9880d681SAndroid Build Coastguard Worker   // Attempt to delete instructions using bisection. This should help out nasty
830*9880d681SAndroid Build Coastguard Worker   // cases with large basic blocks where the problem is at one end.
831*9880d681SAndroid Build Coastguard Worker   if (!BugpointIsInterrupted)
832*9880d681SAndroid Build Coastguard Worker     ReduceInsts(BD, TestFn, Error);
833*9880d681SAndroid Build Coastguard Worker 
834*9880d681SAndroid Build Coastguard Worker   if (!NoNamedMDRM) {
835*9880d681SAndroid Build Coastguard Worker     if (!BugpointIsInterrupted) {
836*9880d681SAndroid Build Coastguard Worker       // Try to reduce the amount of global metadata (particularly debug info),
837*9880d681SAndroid Build Coastguard Worker       // by dropping global named metadata that anchors them
838*9880d681SAndroid Build Coastguard Worker       outs() << "\n*** Attempting to remove named metadata: ";
839*9880d681SAndroid Build Coastguard Worker       std::vector<std::string> NamedMDNames;
840*9880d681SAndroid Build Coastguard Worker       for (auto &NamedMD : BD.getProgram()->named_metadata())
841*9880d681SAndroid Build Coastguard Worker         NamedMDNames.push_back(NamedMD.getName().str());
842*9880d681SAndroid Build Coastguard Worker       ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames, Error);
843*9880d681SAndroid Build Coastguard Worker     }
844*9880d681SAndroid Build Coastguard Worker 
845*9880d681SAndroid Build Coastguard Worker     if (!BugpointIsInterrupted) {
846*9880d681SAndroid Build Coastguard Worker       // Now that we quickly dropped all the named metadata that doesn't
847*9880d681SAndroid Build Coastguard Worker       // contribute to the crash, bisect the operands of the remaining ones
848*9880d681SAndroid Build Coastguard Worker       std::vector<const MDNode *> NamedMDOps;
849*9880d681SAndroid Build Coastguard Worker       for (auto &NamedMD : BD.getProgram()->named_metadata())
850*9880d681SAndroid Build Coastguard Worker         for (auto op : NamedMD.operands())
851*9880d681SAndroid Build Coastguard Worker           NamedMDOps.push_back(op);
852*9880d681SAndroid Build Coastguard Worker       ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps, Error);
853*9880d681SAndroid Build Coastguard Worker     }
854*9880d681SAndroid Build Coastguard Worker     BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
855*9880d681SAndroid Build Coastguard Worker   }
856*9880d681SAndroid Build Coastguard Worker 
857*9880d681SAndroid Build Coastguard Worker   // Try to clean up the testcase by running funcresolve and globaldce...
858*9880d681SAndroid Build Coastguard Worker   if (!BugpointIsInterrupted) {
859*9880d681SAndroid Build Coastguard Worker     outs() << "\n*** Attempting to perform final cleanups: ";
860*9880d681SAndroid Build Coastguard Worker     Module *M = CloneModule(BD.getProgram()).release();
861*9880d681SAndroid Build Coastguard Worker     M = BD.performFinalCleanups(M, true).release();
862*9880d681SAndroid Build Coastguard Worker 
863*9880d681SAndroid Build Coastguard Worker     // Find out if the pass still crashes on the cleaned up program...
864*9880d681SAndroid Build Coastguard Worker     if (TestFn(BD, M)) {
865*9880d681SAndroid Build Coastguard Worker       BD.setNewProgram(M);     // Yup, it does, keep the reduced version...
866*9880d681SAndroid Build Coastguard Worker     } else {
867*9880d681SAndroid Build Coastguard Worker       delete M;
868*9880d681SAndroid Build Coastguard Worker     }
869*9880d681SAndroid Build Coastguard Worker   }
870*9880d681SAndroid Build Coastguard Worker 
871*9880d681SAndroid Build Coastguard Worker   BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
872*9880d681SAndroid Build Coastguard Worker 
873*9880d681SAndroid Build Coastguard Worker   return false;
874*9880d681SAndroid Build Coastguard Worker }
875*9880d681SAndroid Build Coastguard Worker 
TestForOptimizerCrash(const BugDriver & BD,Module * M)876*9880d681SAndroid Build Coastguard Worker static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
877*9880d681SAndroid Build Coastguard Worker   return BD.runPasses(M, BD.getPassesToRun());
878*9880d681SAndroid Build Coastguard Worker }
879*9880d681SAndroid Build Coastguard Worker 
880*9880d681SAndroid Build Coastguard Worker /// debugOptimizerCrash - This method is called when some pass crashes on input.
881*9880d681SAndroid Build Coastguard Worker /// It attempts to prune down the testcase to something reasonable, and figure
882*9880d681SAndroid Build Coastguard Worker /// out exactly which pass is crashing.
883*9880d681SAndroid Build Coastguard Worker ///
debugOptimizerCrash(const std::string & ID)884*9880d681SAndroid Build Coastguard Worker bool BugDriver::debugOptimizerCrash(const std::string &ID) {
885*9880d681SAndroid Build Coastguard Worker   outs() << "\n*** Debugging optimizer crash!\n";
886*9880d681SAndroid Build Coastguard Worker 
887*9880d681SAndroid Build Coastguard Worker   std::string Error;
888*9880d681SAndroid Build Coastguard Worker   // Reduce the list of passes which causes the optimizer to crash...
889*9880d681SAndroid Build Coastguard Worker   if (!BugpointIsInterrupted && !DontReducePassList)
890*9880d681SAndroid Build Coastguard Worker     ReducePassList(*this).reduceList(PassesToRun, Error);
891*9880d681SAndroid Build Coastguard Worker   assert(Error.empty());
892*9880d681SAndroid Build Coastguard Worker 
893*9880d681SAndroid Build Coastguard Worker   outs() << "\n*** Found crashing pass"
894*9880d681SAndroid Build Coastguard Worker          << (PassesToRun.size() == 1 ? ": " : "es: ")
895*9880d681SAndroid Build Coastguard Worker          << getPassesString(PassesToRun) << '\n';
896*9880d681SAndroid Build Coastguard Worker 
897*9880d681SAndroid Build Coastguard Worker   EmitProgressBitcode(Program, ID);
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   bool Success = DebugACrash(*this, TestForOptimizerCrash, Error);
900*9880d681SAndroid Build Coastguard Worker   assert(Error.empty());
901*9880d681SAndroid Build Coastguard Worker   return Success;
902*9880d681SAndroid Build Coastguard Worker }
903*9880d681SAndroid Build Coastguard Worker 
TestForCodeGenCrash(const BugDriver & BD,Module * M)904*9880d681SAndroid Build Coastguard Worker static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
905*9880d681SAndroid Build Coastguard Worker   std::string Error;
906*9880d681SAndroid Build Coastguard Worker   BD.compileProgram(M, &Error);
907*9880d681SAndroid Build Coastguard Worker   if (!Error.empty()) {
908*9880d681SAndroid Build Coastguard Worker     errs() << "<crash>\n";
909*9880d681SAndroid Build Coastguard Worker     return true;  // Tool is still crashing.
910*9880d681SAndroid Build Coastguard Worker   }
911*9880d681SAndroid Build Coastguard Worker   errs() << '\n';
912*9880d681SAndroid Build Coastguard Worker   return false;
913*9880d681SAndroid Build Coastguard Worker }
914*9880d681SAndroid Build Coastguard Worker 
915*9880d681SAndroid Build Coastguard Worker /// debugCodeGeneratorCrash - This method is called when the code generator
916*9880d681SAndroid Build Coastguard Worker /// crashes on an input.  It attempts to reduce the input as much as possible
917*9880d681SAndroid Build Coastguard Worker /// while still causing the code generator to crash.
debugCodeGeneratorCrash(std::string & Error)918*9880d681SAndroid Build Coastguard Worker bool BugDriver::debugCodeGeneratorCrash(std::string &Error) {
919*9880d681SAndroid Build Coastguard Worker   errs() << "*** Debugging code generator crash!\n";
920*9880d681SAndroid Build Coastguard Worker 
921*9880d681SAndroid Build Coastguard Worker   return DebugACrash(*this, TestForCodeGenCrash, Error);
922*9880d681SAndroid Build Coastguard Worker }
923