blob: e973bfef4dc60eed372949860bc3ef78e0462263 [file] [log] [blame]
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner73a6bdd2002-11-20 22:28:10 +00009//
10// This file defines the bugpoint internals that narrow down compilation crashes
11//
12//===----------------------------------------------------------------------===//
13
14#include "BugDriver.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000015#include "ListReducer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "ToolRunner.h"
17#include "llvm/ADT/SmallPtrSet.h"
Keno Fischer34ca8312015-11-06 00:12:50 +000018#include "llvm/ADT/StringSet.h"
Justin Bogner8d0a0812016-09-02 01:21:37 +000019#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000020#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Michael Ilsemane5428042016-10-25 18:44:13 +000023#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Instructions.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000026#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/ValueSymbolTable.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Verifier.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000030#include "llvm/Pass.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/FileUtilities.h"
Chris Lattnerf32939b2003-04-24 23:51:38 +000033#include "llvm/Transforms/Scalar.h"
Daniel Berlin271ca402016-07-27 16:13:25 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000035#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner1d080f22003-04-24 22:24:58 +000036#include <set>
Chris Lattner2f1aa112004-01-14 03:38:37 +000037using namespace llvm;
Chris Lattner73a6bdd2002-11-20 22:28:10 +000038
Andrew Lenharthef9aa122006-03-05 22:21:36 +000039namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +000040cl::opt<bool> KeepMain("keep-main",
41 cl::desc("Force function reduction to keep main"),
42 cl::init(false));
43cl::opt<bool> NoGlobalRM("disable-global-remove",
44 cl::desc("Do not remove global variables"),
45 cl::init(false));
JF Bastienf87e20d2015-04-20 23:42:22 +000046
Justin Bogner8d0a0812016-09-02 01:21:37 +000047cl::opt<bool> ReplaceFuncsWithNull(
48 "replace-funcs-with-null",
49 cl::desc("When stubbing functions, replace all uses will null"),
50 cl::init(false));
51cl::opt<bool> DontReducePassList("disable-pass-list-reduction",
52 cl::desc("Skip pass list reduction steps"),
53 cl::init(false));
Keno Fischer34ca8312015-11-06 00:12:50 +000054
Justin Bogner8d0a0812016-09-02 01:21:37 +000055cl::opt<bool> NoNamedMDRM("disable-namedmd-remove",
56 cl::desc("Do not remove global named metadata"),
57 cl::init(false));
Michael Ilsemane5428042016-10-25 18:44:13 +000058cl::opt<bool> NoStripDebugInfo("disable-strip-debuginfo",
59 cl::desc("Do not strip debug info metadata"),
60 cl::init(false));
61cl::opt<bool> NoStripDebugTypeInfo("disable-strip-debug-types",
62 cl::desc("Do not strip debug type info metadata"),
63 cl::init(false));
Justin Bogner8d0a0812016-09-02 01:21:37 +000064cl::opt<bool> VerboseErrors("verbose-errors",
Sebastian Pop8f7d0192016-07-15 23:15:06 +000065 cl::desc("Print the output of crashing program"),
66 cl::init(false));
Andrew Lenharthef9aa122006-03-05 22:21:36 +000067}
68
Brian Gaeke960707c2003-11-11 22:41:34 +000069namespace llvm {
Justin Bogner8d0a0812016-09-02 01:21:37 +000070class ReducePassList : public ListReducer<std::string> {
71 BugDriver &BD;
Misha Brukman650ba8e2005-04-22 00:00:37 +000072
Justin Bogner8d0a0812016-09-02 01:21:37 +000073public:
74 ReducePassList(BugDriver &bd) : BD(bd) {}
75
Justin Bogner1c039152016-09-06 17:18:22 +000076 // 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;
Justin Bogner8d0a0812016-09-02 01:21:37 +000081};
Chris Lattner2f1aa112004-01-14 03:38:37 +000082}
Chris Lattner1d080f22003-04-24 22:24:58 +000083
Justin Bogner1c039152016-09-06 17:18:22 +000084Expected<ReducePassList::TestResult>
Rafael Espindola33e81a82010-08-08 03:55:08 +000085ReducePassList::doTest(std::vector<std::string> &Prefix,
Justin Bogner1c039152016-09-06 17:18:22 +000086 std::vector<std::string> &Suffix) {
Rafael Espindolabb876652013-06-17 19:33:18 +000087 std::string PrefixOutput;
Rafael Espindola2c8bcab2018-02-14 19:58:41 +000088 std::unique_ptr<Module> OrigProgram;
Chris Lattner1d080f22003-04-24 22:24:58 +000089 if (!Prefix.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +000090 outs() << "Checking to see if these passes crash: "
91 << getPassesString(Prefix) << ": ";
Rafael Espindolabb876652013-06-17 19:33:18 +000092 if (BD.runPasses(BD.getProgram(), Prefix, PrefixOutput))
Chris Lattner1d080f22003-04-24 22:24:58 +000093 return KeepPrefix;
Chris Lattnera9656312003-06-02 04:54:29 +000094
Rafael Espindolaf6074ed2018-02-14 21:44:34 +000095 OrigProgram = std::move(BD.Program);
Chris Lattnera9656312003-06-02 04:54:29 +000096
Rafael Espindolaf6074ed2018-02-14 21:44:34 +000097 BD.Program = parseInputFile(PrefixOutput, BD.getContext());
Craig Toppere6cb63e2014-04-25 04:24:47 +000098 if (BD.Program == nullptr) {
Dan Gohmand8db3762009-07-15 16:35:29 +000099 errs() << BD.getToolName() << ": Error reading bitcode file '"
Rafael Espindolabb876652013-06-17 19:33:18 +0000100 << PrefixOutput << "'!\n";
Chris Lattnera9656312003-06-02 04:54:29 +0000101 exit(1);
102 }
Rafael Espindolabb876652013-06-17 19:33:18 +0000103 sys::fs::remove(PrefixOutput);
Chris Lattner1d080f22003-04-24 22:24:58 +0000104 }
105
Justin Bogner8d0a0812016-09-02 01:21:37 +0000106 outs() << "Checking to see if these passes crash: " << getPassesString(Suffix)
107 << ": ";
Misha Brukman650ba8e2005-04-22 00:00:37 +0000108
Rafael Espindola2c8bcab2018-02-14 19:58:41 +0000109 if (BD.runPasses(BD.getProgram(), Suffix))
110 return KeepSuffix; // The suffix crashes alone...
Chris Lattner1d080f22003-04-24 22:24:58 +0000111
112 // Nothing failed, restore state...
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000113 if (OrigProgram)
114 BD.Program = std::move(OrigProgram);
Chris Lattner1d080f22003-04-24 22:24:58 +0000115 return NoFailure;
116}
117
Vedant Kumar08d829d2018-02-08 18:46:49 +0000118using BugTester = bool (*)(const BugDriver &, Module *);
119
Bill Wendling3f833432006-10-25 18:36:14 +0000120namespace {
Vedant Kumar66e85e62018-02-08 20:27:09 +0000121/// ReduceCrashingGlobalInitializers - This works by removing global variable
122/// initializers and seeing if the program still crashes. If it does, then we
123/// keep that program and try again.
124class ReduceCrashingGlobalInitializers : public ListReducer<GlobalVariable *> {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000125 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000126 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000127
128public:
Vedant Kumar66e85e62018-02-08 20:27:09 +0000129 ReduceCrashingGlobalInitializers(BugDriver &bd, BugTester testFn)
Bill Wendling3f833432006-10-25 18:36:14 +0000130 : BD(bd), TestFn(testFn) {}
131
Justin Bogner1c039152016-09-06 17:18:22 +0000132 Expected<TestResult> doTest(std::vector<GlobalVariable *> &Prefix,
133 std::vector<GlobalVariable *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000134 if (!Kept.empty() && TestGlobalVariables(Kept))
135 return KeepSuffix;
136 if (!Prefix.empty() && TestGlobalVariables(Prefix))
137 return KeepPrefix;
138 return NoFailure;
139 }
Bill Wendling3f833432006-10-25 18:36:14 +0000140
Justin Bogner8d0a0812016-09-02 01:21:37 +0000141 bool TestGlobalVariables(std::vector<GlobalVariable *> &GVs);
142};
Bill Wendling3f833432006-10-25 18:36:14 +0000143}
144
Vedant Kumar66e85e62018-02-08 20:27:09 +0000145bool ReduceCrashingGlobalInitializers::TestGlobalVariables(
Justin Bogner8d0a0812016-09-02 01:21:37 +0000146 std::vector<GlobalVariable *> &GVs) {
Bill Wendling3f833432006-10-25 18:36:14 +0000147 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000148 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000149 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Bill Wendling3f833432006-10-25 18:36:14 +0000150
151 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000152 std::set<GlobalVariable *> GVSet;
Bill Wendling3f833432006-10-25 18:36:14 +0000153
154 for (unsigned i = 0, e = GVs.size(); i != e; ++i) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000155 GlobalVariable *CMGV = cast<GlobalVariable>(VMap[GVs[i]]);
Bill Wendling3f833432006-10-25 18:36:14 +0000156 assert(CMGV && "Global Variable not in module?!");
157 GVSet.insert(CMGV);
158 }
159
Dan Gohmanee051522009-07-16 15:30:09 +0000160 outs() << "Checking for crash with only these global variables: ";
Bill Wendling3f833432006-10-25 18:36:14 +0000161 PrintGlobalVariableList(GVs);
Dan Gohmanee051522009-07-16 15:30:09 +0000162 outs() << ": ";
Bill Wendling3f833432006-10-25 18:36:14 +0000163
164 // Loop over and delete any global variables which we aren't supposed to be
165 // playing with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000166 for (GlobalVariable &I : M->globals())
167 if (I.hasInitializer() && !GVSet.count(&I)) {
Hal Finkel28ad2b42015-11-26 19:23:49 +0000168 DeleteGlobalInitializer(&I);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000169 I.setLinkage(GlobalValue::ExternalLinkage);
Justin Lebar2a445cf2016-06-15 23:20:12 +0000170 I.setComdat(nullptr);
Bill Wendling3f833432006-10-25 18:36:14 +0000171 }
172
173 // Try running the hacked up program...
Vedant Kumar66e85e62018-02-08 20:27:09 +0000174 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000175 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Bill Wendling3f833432006-10-25 18:36:14 +0000176
177 // Make sure to use global variable pointers that point into the now-current
178 // module.
179 GVs.assign(GVSet.begin(), GVSet.end());
180 return true;
181 }
182
Bill Wendling3f833432006-10-25 18:36:14 +0000183 return false;
184}
185
David Blaikiea379b1812011-12-20 02:50:00 +0000186namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000187/// ReduceCrashingFunctions reducer - This works by removing functions and
188/// seeing if the program still crashes. If it does, then keep the newer,
189/// smaller program.
190///
191class ReduceCrashingFunctions : public ListReducer<Function *> {
192 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000193 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000194
195public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000196 ReduceCrashingFunctions(BugDriver &bd, BugTester testFn)
Chris Lattner8bda4c42004-02-18 23:26:28 +0000197 : BD(bd), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000198
Justin Bogner1c039152016-09-06 17:18:22 +0000199 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200 std::vector<Function *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000201 if (!Kept.empty() && TestFuncs(Kept))
202 return KeepSuffix;
203 if (!Prefix.empty() && TestFuncs(Prefix))
204 return KeepPrefix;
205 return NoFailure;
206 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000207
Justin Bogner8d0a0812016-09-02 01:21:37 +0000208 bool TestFuncs(std::vector<Function *> &Prefix);
209};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000210}
Chris Lattner1d080f22003-04-24 22:24:58 +0000211
Justin Bogner8d0a0812016-09-02 01:21:37 +0000212static void RemoveFunctionReferences(Module *M, const char *Name) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000213 auto *UsedVar = M->getGlobalVariable(Name, true);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000214 if (!UsedVar || !UsedVar->hasInitializer())
215 return;
JF Bastienf87e20d2015-04-20 23:42:22 +0000216 if (isa<ConstantAggregateZero>(UsedVar->getInitializer())) {
217 assert(UsedVar->use_empty());
218 UsedVar->eraseFromParent();
219 return;
220 }
221 auto *OldUsedVal = cast<ConstantArray>(UsedVar->getInitializer());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000222 std::vector<Constant *> Used;
223 for (Value *V : OldUsedVal->operand_values()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000224 Constant *Op = cast<Constant>(V->stripPointerCasts());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000225 if (!Op->isNullValue()) {
JF Bastienf87e20d2015-04-20 23:42:22 +0000226 Used.push_back(cast<Constant>(V));
227 }
228 }
229 auto *NewValElemTy = OldUsedVal->getType()->getElementType();
230 auto *NewValTy = ArrayType::get(NewValElemTy, Used.size());
231 auto *NewUsedVal = ConstantArray::get(NewValTy, Used);
232 UsedVar->mutateType(NewUsedVal->getType()->getPointerTo());
233 UsedVar->setInitializer(NewUsedVal);
234}
235
Justin Bogner8d0a0812016-09-02 01:21:37 +0000236bool ReduceCrashingFunctions::TestFuncs(std::vector<Function *> &Funcs) {
Dmitri Gribenko6e0520e2013-09-02 01:18:56 +0000237 // If main isn't present, claim there is no problem.
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000238 if (KeepMain && !is_contained(Funcs, BD.getProgram().getFunction("main")))
Andrew Lenharthef9aa122006-03-05 22:21:36 +0000239 return false;
240
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000241 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000242 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000243 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000244
Chris Lattner1d080f22003-04-24 22:24:58 +0000245 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000246 std::set<Function *> Functions;
Chris Lattner1d080f22003-04-24 22:24:58 +0000247 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000248 Function *CMF = cast<Function>(VMap[Funcs[i]]);
Chris Lattner1d080f22003-04-24 22:24:58 +0000249 assert(CMF && "Function not in module?!");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000250 assert(CMF->getFunctionType() == Funcs[i]->getFunctionType() && "wrong ty");
Dan Gohmanbcad7182009-03-06 02:16:23 +0000251 assert(CMF->getName() == Funcs[i]->getName() && "wrong name");
Chris Lattnerde39f2b2003-04-24 22:54:06 +0000252 Functions.insert(CMF);
Chris Lattner1d080f22003-04-24 22:24:58 +0000253 }
254
Dan Gohmanee051522009-07-16 15:30:09 +0000255 outs() << "Checking for crash with only these functions: ";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000256 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000257 outs() << ": ";
JF Bastienf87e20d2015-04-20 23:42:22 +0000258 if (!ReplaceFuncsWithNull) {
259 // Loop over and delete any functions which we aren't supposed to be playing
260 // with...
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000261 for (Function &I : *M)
262 if (!I.isDeclaration() && !Functions.count(&I))
263 DeleteFunctionBody(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000264 } else {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000265 std::vector<GlobalValue *> ToRemove;
JF Bastienf87e20d2015-04-20 23:42:22 +0000266 // First, remove aliases to functions we're about to purge.
267 for (GlobalAlias &Alias : M->aliases()) {
David Majnemer95549492016-05-04 00:20:48 +0000268 GlobalObject *Root = Alias.getBaseObject();
269 Function *F = dyn_cast_or_null<Function>(Root);
JF Bastienf87e20d2015-04-20 23:42:22 +0000270 if (F) {
271 if (Functions.count(F))
272 // We're keeping this function.
273 continue;
274 } else if (Root->isNullValue()) {
275 // This referenced a globalalias that we've already replaced,
276 // so we still need to replace this alias.
277 } else if (!F) {
278 // Not a function, therefore not something we mess with.
279 continue;
280 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000281
JF Bastienf87e20d2015-04-20 23:42:22 +0000282 PointerType *Ty = cast<PointerType>(Alias.getType());
283 Constant *Replacement = ConstantPointerNull::get(Ty);
284 Alias.replaceAllUsesWith(Replacement);
285 ToRemove.push_back(&Alias);
286 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000287
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000288 for (Function &I : *M) {
289 if (!I.isDeclaration() && !Functions.count(&I)) {
290 PointerType *Ty = cast<PointerType>(I.getType());
JF Bastienf87e20d2015-04-20 23:42:22 +0000291 Constant *Replacement = ConstantPointerNull::get(Ty);
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000292 I.replaceAllUsesWith(Replacement);
293 ToRemove.push_back(&I);
JF Bastienf87e20d2015-04-20 23:42:22 +0000294 }
295 }
296
297 for (auto *F : ToRemove) {
298 F->eraseFromParent();
299 }
300
301 // Finally, remove any null members from any global intrinsic.
Rafael Espindola15647b72018-02-14 20:21:20 +0000302 RemoveFunctionReferences(M.get(), "llvm.used");
303 RemoveFunctionReferences(M.get(), "llvm.compiler.used");
JF Bastienf87e20d2015-04-20 23:42:22 +0000304 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000305 // Try running the hacked up program...
Rafael Espindola15647b72018-02-14 20:21:20 +0000306 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000307 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Chris Lattner1d080f22003-04-24 22:24:58 +0000308
309 // Make sure to use function pointers that point into the now-current
310 // module.
311 Funcs.assign(Functions.begin(), Functions.end());
312 return true;
313 }
Chris Lattner1d080f22003-04-24 22:24:58 +0000314 return false;
315}
316
Chris Lattner1942f982004-02-18 21:29:46 +0000317namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000318/// Simplify the CFG without completely destroying it.
319/// This is not well defined, but basically comes down to "try to eliminate
320/// unreachable blocks and constant fold terminators without deciding that
321/// certain undefined behavior cuts off the program at the legs".
322void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
323 if (F.empty())
324 return;
325
326 for (auto *BB : BBs) {
327 ConstantFoldTerminator(BB);
328 MergeBlockIntoPredecessor(BB);
329 }
330
331 // Remove unreachable blocks
332 // removeUnreachableBlocks can't be used here, it will turn various
333 // undefined behavior into unreachables, but bugpoint was the thing that
334 // generated the undefined behavior, and we don't want it to kill the entire
335 // program.
336 SmallPtrSet<BasicBlock *, 16> Visited;
337 for (auto *BB : depth_first(&F.getEntryBlock()))
338 Visited.insert(BB);
339
340 SmallVector<BasicBlock *, 16> Unreachable;
341 for (auto &BB : F)
342 if (!Visited.count(&BB))
343 Unreachable.push_back(&BB);
344
345 // The dead BB's may be in a dead cycle or otherwise have references to each
346 // other. Because of this, we have to drop all references first, then delete
347 // them all at once.
Justin Bogner8d0a0812016-09-02 01:21:37 +0000348 for (auto *BB : Unreachable) {
Daniel Berlin60606262016-07-28 22:29:25 +0000349 for (BasicBlock *Successor : successors(&*BB))
350 if (Visited.count(Successor))
351 Successor->removePredecessor(&*BB);
352 BB->dropAllReferences();
353 }
354 for (auto *BB : Unreachable)
355 BB->eraseFromParent();
356}
Justin Bogner8d0a0812016-09-02 01:21:37 +0000357/// ReduceCrashingBlocks reducer - This works by setting the terminators of
358/// all terminators except the specified basic blocks to a 'ret' instruction,
359/// then running the simplify-cfg pass. This has the effect of chopping up
360/// the CFG really fast which can reduce large functions quickly.
361///
362class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
363 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000364 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000365
366public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000367 ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
Daniel Berlin60606262016-07-28 22:29:25 +0000368 : BD(BD), TestFn(testFn) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000369
Justin Bogner1c039152016-09-06 17:18:22 +0000370 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
371 std::vector<const BasicBlock *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000372 if (!Kept.empty() && TestBlocks(Kept))
373 return KeepSuffix;
374 if (!Prefix.empty() && TestBlocks(Prefix))
375 return KeepPrefix;
376 return NoFailure;
377 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000378
Justin Bogner8d0a0812016-09-02 01:21:37 +0000379 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
380};
Chris Lattner2f1aa112004-01-14 03:38:37 +0000381}
Chris Lattnerf32939b2003-04-24 23:51:38 +0000382
Justin Bogner8d0a0812016-09-02 01:21:37 +0000383bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000384 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000385 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000386 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000387
Chris Lattnerf32939b2003-04-24 23:51:38 +0000388 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000389 SmallPtrSet<BasicBlock *, 8> Blocks;
Nick Lewyckyb294e312009-04-04 09:39:23 +0000390 for (unsigned i = 0, e = BBs.size(); i != e; ++i)
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000391 Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000392
Dan Gohmanee051522009-07-16 15:30:09 +0000393 outs() << "Checking for crash with only these blocks:";
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000394 unsigned NumPrint = Blocks.size();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000395 if (NumPrint > 10)
396 NumPrint = 10;
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000397 for (unsigned i = 0, e = NumPrint; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000398 outs() << " " << BBs[i]->getName();
Chris Lattner4f50ebd2003-10-27 04:44:59 +0000399 if (NumPrint < Blocks.size())
Dan Gohmanee051522009-07-16 15:30:09 +0000400 outs() << "... <" << Blocks.size() << " total>";
401 outs() << ": ";
Chris Lattnerf32939b2003-04-24 23:51:38 +0000402
403 // Loop over and delete any hack up any blocks that are not listed...
Vedant Kumare84e7672018-02-09 05:09:50 +0000404 for (Function &F : M->functions()) {
405 for (BasicBlock &BB : F) {
406 if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
Chris Lattnerf32939b2003-04-24 23:51:38 +0000407 // Loop over all of the successors of this block, deleting any PHI nodes
408 // that might include it.
Vedant Kumare84e7672018-02-09 05:09:50 +0000409 for (BasicBlock *Succ : successors(&BB))
410 Succ->removePredecessor(&BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000411
Vedant Kumare84e7672018-02-09 05:09:50 +0000412 TerminatorInst *BBTerm = BB.getTerminator();
Philip Reames29e641c2016-06-29 00:15:35 +0000413 if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
David Majnemer189d7da2015-11-08 04:16:12 +0000414 continue;
Philip Reames29e641c2016-06-29 00:15:35 +0000415 if (!BBTerm->getType()->isVoidTy())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000416 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
Chris Lattner7b233af2003-11-22 02:10:38 +0000417
Chris Lattner7855a5c2008-04-28 00:04:58 +0000418 // Replace the old terminator instruction.
Vedant Kumare84e7672018-02-09 05:09:50 +0000419 BB.getInstList().pop_back();
420 new UnreachableInst(BB.getContext(), &BB);
Chris Lattnerf32939b2003-04-24 23:51:38 +0000421 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000422 }
423 }
Chris Lattnerf32939b2003-04-24 23:51:38 +0000424
425 // The CFG Simplifier pass may delete one of the basic blocks we are
426 // interested in. If it does we need to take the block out of the list. Make
427 // a "persistent mapping" by turning basic blocks into <function, name> pairs.
428 // This won't work well if blocks are unnamed, but that is just the risk we
Vedant Kumare84e7672018-02-09 05:09:50 +0000429 // have to take. FIXME: Can we just name the blocks?
Justin Bogner8d0a0812016-09-02 01:21:37 +0000430 std::vector<std::pair<std::string, std::string>> BlockInfo;
Chris Lattnerf32939b2003-04-24 23:51:38 +0000431
Craig Topper46276792014-08-24 23:23:06 +0000432 for (BasicBlock *BB : Blocks)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000433 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
Justin Bogner8d0a0812016-09-02 01:21:37 +0000434
Daniel Berlin60606262016-07-28 22:29:25 +0000435 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000436 for (auto &F : *M) {
Daniel Berlin60606262016-07-28 22:29:25 +0000437 for (auto &BB : F)
438 if (!Blocks.count(&BB))
439 ToProcess.push_back(&BB);
440 simpleSimplifyCfg(F, ToProcess);
441 ToProcess.clear();
442 }
443 // Verify we didn't break anything
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000444 std::vector<std::string> Passes;
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000445 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000446 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000447 if (!New) {
Daniel Berlin60606262016-07-28 22:29:25 +0000448 errs() << "verify failed!\n";
Rafael Espindolad1e241a2010-08-10 15:46:11 +0000449 exit(1);
450 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000451 M = std::move(New);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000452
Chris Lattnerf32939b2003-04-24 23:51:38 +0000453 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000454 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000455 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Chris Lattnerf32939b2003-04-24 23:51:38 +0000456
457 // Make sure to use basic block pointers that point into the now-current
458 // module, and that they don't include any deleted blocks.
459 BBs.clear();
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000460 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Vedant Kumare84e7672018-02-09 05:09:50 +0000461 for (const auto &BI : BlockInfo) {
462 Function *F = cast<Function>(GST.lookup(BI.first));
463 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Owen Anderson55f1c092009-08-13 21:58:54 +0000464 if (V && V->getType() == Type::getLabelTy(V->getContext()))
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000465 BBs.push_back(cast<BasicBlock>(V));
Chris Lattnerf32939b2003-04-24 23:51:38 +0000466 }
467 return true;
468 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000469 // It didn't crash, try something else.
Chris Lattnerf32939b2003-04-24 23:51:38 +0000470 return false;
471}
472
Nick Lewycky6e090c92009-05-25 05:30:00 +0000473namespace {
Daniel Berlin271ca402016-07-27 16:13:25 +0000474/// ReduceCrashingConditionals reducer - This works by changing
475/// conditional branches to unconditional ones, then simplifying the CFG
476/// This has the effect of chopping up the CFG really fast which can reduce
477/// large functions quickly.
478///
479class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
480 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000481 BugTester TestFn;
Daniel Berlin271ca402016-07-27 16:13:25 +0000482 bool Direction;
483
484public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000485 ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
Daniel Berlin271ca402016-07-27 16:13:25 +0000486 : BD(bd), TestFn(testFn), Direction(Direction) {}
487
Justin Bogner1c039152016-09-06 17:18:22 +0000488 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
489 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin271ca402016-07-27 16:13:25 +0000490 if (!Kept.empty() && TestBlocks(Kept))
491 return KeepSuffix;
492 if (!Prefix.empty() && TestBlocks(Prefix))
493 return KeepPrefix;
494 return NoFailure;
495 }
496
497 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
498};
499}
500
501bool ReduceCrashingConditionals::TestBlocks(
502 std::vector<const BasicBlock *> &BBs) {
503 // Clone the program to try hacking it apart...
504 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000505 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Daniel Berlin271ca402016-07-27 16:13:25 +0000506
507 // Convert list to set for fast lookup...
508 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000509 for (const auto *BB : BBs)
Daniel Berlin271ca402016-07-27 16:13:25 +0000510 Blocks.insert(cast<BasicBlock>(VMap[BB]));
511
512 outs() << "Checking for crash with changing conditionals to always jump to "
513 << (Direction ? "true" : "false") << ":";
514 unsigned NumPrint = Blocks.size();
515 if (NumPrint > 10)
516 NumPrint = 10;
517 for (unsigned i = 0, e = NumPrint; i != e; ++i)
518 outs() << " " << BBs[i]->getName();
519 if (NumPrint < Blocks.size())
520 outs() << "... <" << Blocks.size() << " total>";
521 outs() << ": ";
522
523 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000524 for (auto &F : *M)
Daniel Berlin271ca402016-07-27 16:13:25 +0000525 for (auto &BB : F)
526 if (!Blocks.count(&BB)) {
527 auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
528 if (!BR || !BR->isConditional())
529 continue;
530 if (Direction)
531 BR->setCondition(ConstantInt::getTrue(BR->getContext()));
532 else
533 BR->setCondition(ConstantInt::getFalse(BR->getContext()));
534 }
535
536 // The following may destroy some blocks, so we save them first
537 std::vector<std::pair<std::string, std::string>> BlockInfo;
538
539 for (const BasicBlock *BB : Blocks)
540 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
541
542 SmallVector<BasicBlock *, 16> ToProcess;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000543 for (auto &F : *M) {
Daniel Berlin271ca402016-07-27 16:13:25 +0000544 for (auto &BB : F)
545 if (!Blocks.count(&BB))
546 ToProcess.push_back(&BB);
547 simpleSimplifyCfg(F, ToProcess);
548 ToProcess.clear();
549 }
550 // Verify we didn't break anything
551 std::vector<std::string> Passes;
552 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000553 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin271ca402016-07-27 16:13:25 +0000554 if (!New) {
555 errs() << "verify failed!\n";
556 exit(1);
557 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000558 M = std::move(New);
Daniel Berlin271ca402016-07-27 16:13:25 +0000559
560 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000561 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000562 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Daniel Berlin271ca402016-07-27 16:13:25 +0000563
564 // Make sure to use basic block pointers that point into the now-current
565 // module, and that they don't include any deleted blocks.
566 BBs.clear();
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000567 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Daniel Berlin271ca402016-07-27 16:13:25 +0000568 for (auto &BI : BlockInfo) {
569 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000570 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin271ca402016-07-27 16:13:25 +0000571 if (V && V->getType() == Type::getLabelTy(V->getContext()))
572 BBs.push_back(cast<BasicBlock>(V));
573 }
574 return true;
575 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000576 // It didn't crash, try something else.
Daniel Berlin271ca402016-07-27 16:13:25 +0000577 return false;
578}
579
580namespace {
Daniel Berlin60606262016-07-28 22:29:25 +0000581/// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
582/// in the program.
583
584class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
585 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000586 BugTester TestFn;
Daniel Berlin60606262016-07-28 22:29:25 +0000587 TargetTransformInfo TTI;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000588
Daniel Berlin60606262016-07-28 22:29:25 +0000589public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000590 ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000591 : BD(bd), TestFn(testFn), TTI(bd.getProgram().getDataLayout()) {}
Daniel Berlin60606262016-07-28 22:29:25 +0000592
Justin Bogner1c039152016-09-06 17:18:22 +0000593 Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
594 std::vector<const BasicBlock *> &Kept) override {
Daniel Berlin60606262016-07-28 22:29:25 +0000595 if (!Kept.empty() && TestBlocks(Kept))
596 return KeepSuffix;
597 if (!Prefix.empty() && TestBlocks(Prefix))
598 return KeepPrefix;
599 return NoFailure;
600 }
601
602 bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
603};
604}
605
Justin Bogner8d0a0812016-09-02 01:21:37 +0000606bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
Daniel Berlin60606262016-07-28 22:29:25 +0000607 // Clone the program to try hacking it apart...
608 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000609 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Daniel Berlin60606262016-07-28 22:29:25 +0000610
611 // Convert list to set for fast lookup...
612 SmallPtrSet<const BasicBlock *, 8> Blocks;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000613 for (const auto *BB : BBs)
Daniel Berlin60606262016-07-28 22:29:25 +0000614 Blocks.insert(cast<BasicBlock>(VMap[BB]));
615
616 outs() << "Checking for crash with CFG simplifying:";
617 unsigned NumPrint = Blocks.size();
618 if (NumPrint > 10)
619 NumPrint = 10;
620 for (unsigned i = 0, e = NumPrint; i != e; ++i)
621 outs() << " " << BBs[i]->getName();
622 if (NumPrint < Blocks.size())
623 outs() << "... <" << Blocks.size() << " total>";
624 outs() << ": ";
625
Justin Bogner8d0a0812016-09-02 01:21:37 +0000626 // The following may destroy some blocks, so we save them first
Daniel Berlin60606262016-07-28 22:29:25 +0000627 std::vector<std::pair<std::string, std::string>> BlockInfo;
628
629 for (const BasicBlock *BB : Blocks)
630 BlockInfo.emplace_back(BB->getParent()->getName(), BB->getName());
631
Daniel Berlin60606262016-07-28 22:29:25 +0000632 // Loop over and delete any hack up any blocks that are not listed...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000633 for (auto &F : *M)
634 // Loop over all of the basic blocks and remove them if they are unneeded.
635 for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
636 if (!Blocks.count(&*BBIt)) {
637 ++BBIt;
638 continue;
639 }
Sanjay Patel4c33d522017-10-04 20:26:25 +0000640 simplifyCFG(&*BBIt++, TTI);
Justin Bogner8d0a0812016-09-02 01:21:37 +0000641 }
Daniel Berlin60606262016-07-28 22:29:25 +0000642 // Verify we didn't break anything
643 std::vector<std::string> Passes;
644 Passes.push_back("verify");
Vedant Kumare84e7672018-02-09 05:09:50 +0000645 std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
Daniel Berlin60606262016-07-28 22:29:25 +0000646 if (!New) {
647 errs() << "verify failed!\n";
648 exit(1);
649 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000650 M = std::move(New);
Daniel Berlin60606262016-07-28 22:29:25 +0000651
652 // Try running on the hacked up program...
Vedant Kumare84e7672018-02-09 05:09:50 +0000653 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000654 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Daniel Berlin60606262016-07-28 22:29:25 +0000655
656 // Make sure to use basic block pointers that point into the now-current
657 // module, and that they don't include any deleted blocks.
658 BBs.clear();
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000659 const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000660 for (auto &BI : BlockInfo) {
Daniel Berlin60606262016-07-28 22:29:25 +0000661 auto *F = cast<Function>(GST.lookup(BI.first));
Mehdi Aminia53d49e2016-09-17 06:00:02 +0000662 Value *V = F->getValueSymbolTable()->lookup(BI.second);
Daniel Berlin60606262016-07-28 22:29:25 +0000663 if (V && V->getType() == Type::getLabelTy(V->getContext()))
664 BBs.push_back(cast<BasicBlock>(V));
665 }
666 return true;
667 }
Vedant Kumare84e7672018-02-09 05:09:50 +0000668 // It didn't crash, try something else.
Daniel Berlin60606262016-07-28 22:29:25 +0000669 return false;
670}
671
672namespace {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000673/// ReduceCrashingInstructions reducer - This works by removing the specified
674/// non-terminator instructions and replacing them with undef.
675///
676class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
677 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000678 BugTester TestFn;
Justin Bogner8d0a0812016-09-02 01:21:37 +0000679
680public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000681 ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
Nick Lewycky6e090c92009-05-25 05:30:00 +0000682 : BD(bd), TestFn(testFn) {}
683
Justin Bogner1c039152016-09-06 17:18:22 +0000684 Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
685 std::vector<const Instruction *> &Kept) override {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000686 if (!Kept.empty() && TestInsts(Kept))
687 return KeepSuffix;
688 if (!Prefix.empty() && TestInsts(Prefix))
689 return KeepPrefix;
690 return NoFailure;
691 }
Nick Lewycky6e090c92009-05-25 05:30:00 +0000692
Justin Bogner8d0a0812016-09-02 01:21:37 +0000693 bool TestInsts(std::vector<const Instruction *> &Prefix);
694};
Nick Lewycky6e090c92009-05-25 05:30:00 +0000695}
696
Justin Bogner8d0a0812016-09-02 01:21:37 +0000697bool ReduceCrashingInstructions::TestInsts(
698 std::vector<const Instruction *> &Insts) {
Nick Lewycky6e090c92009-05-25 05:30:00 +0000699 // Clone the program to try hacking it apart...
Rafael Espindola229e38f2010-10-13 01:36:30 +0000700 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000701 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000702
703 // Convert list to set for fast lookup...
Justin Bogner8d0a0812016-09-02 01:21:37 +0000704 SmallPtrSet<Instruction *, 32> Instructions;
Nick Lewycky6e090c92009-05-25 05:30:00 +0000705 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000706 assert(!Insts[i]->isTerminator());
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000707 Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000708 }
709
Dan Gohmanee051522009-07-16 15:30:09 +0000710 outs() << "Checking for crash with only " << Instructions.size();
Nick Lewycky6e090c92009-05-25 05:30:00 +0000711 if (Instructions.size() == 1)
Dan Gohmanee051522009-07-16 15:30:09 +0000712 outs() << " instruction: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000713 else
Dan Gohmanee051522009-07-16 15:30:09 +0000714 outs() << " instructions: ";
Nick Lewycky6e090c92009-05-25 05:30:00 +0000715
716 for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
717 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
718 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000719 Instruction *Inst = &*I++;
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000720 if (!Instructions.count(Inst) && !Inst->isTerminator() &&
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +0000721 !Inst->isEHPad() && !Inst->getType()->isTokenTy() &&
722 !Inst->isSwiftError()) {
Philip Reames29e641c2016-06-29 00:15:35 +0000723 if (!Inst->getType()->isVoidTy())
Nick Lewycky6e090c92009-05-25 05:30:00 +0000724 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
725 Inst->eraseFromParent();
726 }
727 }
728
729 // Verify that this is still valid.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000730 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000731 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Nick Lewycky6e090c92009-05-25 05:30:00 +0000732 Passes.run(*M);
733
734 // Try running on the hacked up program...
Rafael Espindola19d86552018-02-14 20:25:18 +0000735 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000736 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Nick Lewycky6e090c92009-05-25 05:30:00 +0000737
738 // Make sure to use instruction pointers that point into the now-current
739 // module, and that they don't include any deleted blocks.
740 Insts.clear();
Craig Topper46276792014-08-24 23:23:06 +0000741 for (Instruction *Inst : Instructions)
742 Insts.push_back(Inst);
Nick Lewycky6e090c92009-05-25 05:30:00 +0000743 return true;
744 }
Rafael Espindola19d86552018-02-14 20:25:18 +0000745 // It didn't crash, try something else.
Nick Lewycky6e090c92009-05-25 05:30:00 +0000746 return false;
747}
748
Keno Fischer34ca8312015-11-06 00:12:50 +0000749namespace {
750// Reduce the list of Named Metadata nodes. We keep this as a list of
751// names to avoid having to convert back and forth every time.
752class ReduceCrashingNamedMD : public ListReducer<std::string> {
753 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000754 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000755
756public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000757 ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000758 : BD(bd), TestFn(testFn) {}
759
Justin Bogner1c039152016-09-06 17:18:22 +0000760 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
761 std::vector<std::string> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000762 if (!Kept.empty() && TestNamedMDs(Kept))
763 return KeepSuffix;
764 if (!Prefix.empty() && TestNamedMDs(Prefix))
765 return KeepPrefix;
766 return NoFailure;
767 }
768
769 bool TestNamedMDs(std::vector<std::string> &NamedMDs);
770};
771}
772
773bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
774
775 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000776 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Keno Fischer34ca8312015-11-06 00:12:50 +0000777
778 outs() << "Checking for crash with only these named metadata nodes:";
779 unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
780 for (unsigned i = 0, e = NumPrint; i != e; ++i)
781 outs() << " " << NamedMDs[i];
782 if (NumPrint < NamedMDs.size())
783 outs() << "... <" << NamedMDs.size() << " total>";
784 outs() << ": ";
785
786 // Make a StringMap for faster lookup
787 StringSet<> Names;
788 for (const std::string &Name : NamedMDs)
789 Names.insert(Name);
790
791 // First collect all the metadata to delete in a vector, then
792 // delete them all at once to avoid invalidating the iterator
793 std::vector<NamedMDNode *> ToDelete;
794 ToDelete.reserve(M->named_metadata_size() - Names.size());
795 for (auto &NamedMD : M->named_metadata())
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000796 // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
797 if (!Names.count(NamedMD.getName()) &&
798 (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
Keno Fischer34ca8312015-11-06 00:12:50 +0000799 ToDelete.push_back(&NamedMD);
800
801 for (auto *NamedMD : ToDelete)
802 NamedMD->eraseFromParent();
803
804 // Verify that this is still valid.
805 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000806 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000807 Passes.run(*M);
808
809 // Try running on the hacked up program...
Rafael Espindola29118412018-02-14 20:53:38 +0000810 if (TestFn(BD, M.get())) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000811 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Keno Fischer34ca8312015-11-06 00:12:50 +0000812 return true;
813 }
Keno Fischer34ca8312015-11-06 00:12:50 +0000814 return false;
815}
816
817namespace {
818// Reduce the list of operands to named metadata nodes
819class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
820 BugDriver &BD;
Vedant Kumar08d829d2018-02-08 18:46:49 +0000821 BugTester TestFn;
Keno Fischer34ca8312015-11-06 00:12:50 +0000822
823public:
Vedant Kumar08d829d2018-02-08 18:46:49 +0000824 ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
Keno Fischer34ca8312015-11-06 00:12:50 +0000825 : BD(bd), TestFn(testFn) {}
826
Justin Bogner1c039152016-09-06 17:18:22 +0000827 Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
828 std::vector<const MDNode *> &Kept) override {
Keno Fischer34ca8312015-11-06 00:12:50 +0000829 if (!Kept.empty() && TestNamedMDOps(Kept))
830 return KeepSuffix;
831 if (!Prefix.empty() && TestNamedMDOps(Prefix))
832 return KeepPrefix;
833 return NoFailure;
834 }
835
836 bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
837};
838}
839
840bool ReduceCrashingNamedMDOps::TestNamedMDOps(
841 std::vector<const MDNode *> &NamedMDOps) {
842 // Convert list to set for fast lookup...
Matthias Braunb30f2f512016-01-30 01:24:31 +0000843 SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
Keno Fischer34ca8312015-11-06 00:12:50 +0000844 for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
845 OldMDNodeOps.insert(NamedMDOps[i]);
846 }
847
848 outs() << "Checking for crash with only " << OldMDNodeOps.size();
849 if (OldMDNodeOps.size() == 1)
850 outs() << " named metadata operand: ";
851 else
852 outs() << " named metadata operands: ";
853
854 ValueToValueMapTy VMap;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000855 std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
Keno Fischer34ca8312015-11-06 00:12:50 +0000856
857 // This is a little wasteful. In the future it might be good if we could have
858 // these dropped during cloning.
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000859 for (auto &NamedMD : BD.getProgram().named_metadata()) {
Keno Fischer34ca8312015-11-06 00:12:50 +0000860 // Drop the old one and create a new one
861 M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
862 NamedMDNode *NewNamedMDNode =
863 M->getOrInsertNamedMetadata(NamedMD.getName());
864 for (MDNode *op : NamedMD.operands())
865 if (OldMDNodeOps.count(op))
866 NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
867 }
868
869 // Verify that this is still valid.
870 legacy::PassManager Passes;
Adrian Prantl919bdf12016-10-18 16:24:43 +0000871 Passes.add(createVerifierPass(/*FatalErrors=*/false));
Keno Fischer34ca8312015-11-06 00:12:50 +0000872 Passes.run(*M);
873
874 // Try running on the hacked up program...
Rafael Espindola02a3fb12018-02-14 20:59:39 +0000875 if (TestFn(BD, M.get())) {
Keno Fischer34ca8312015-11-06 00:12:50 +0000876 // Make sure to use instruction pointers that point into the now-current
877 // module, and that they don't include any deleted blocks.
878 NamedMDOps.clear();
879 for (const MDNode *Node : OldMDNodeOps)
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000880 NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
Keno Fischer34ca8312015-11-06 00:12:50 +0000881
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000882 BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
Keno Fischer34ca8312015-11-06 00:12:50 +0000883 return true;
884 }
Rafael Espindola02a3fb12018-02-14 20:59:39 +0000885 // It didn't crash, try something else.
Keno Fischer34ca8312015-11-06 00:12:50 +0000886 return false;
887}
888
Vedant Kumar66e85e62018-02-08 20:27:09 +0000889/// Attempt to eliminate as many global initializers as possible.
Vedant Kumar08d829d2018-02-08 18:46:49 +0000890static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000891 Module &OrigM = BD.getProgram();
892 if (OrigM.global_empty())
Vedant Kumar66e85e62018-02-08 20:27:09 +0000893 return Error::success();
Misha Brukman650ba8e2005-04-22 00:00:37 +0000894
Vedant Kumar66e85e62018-02-08 20:27:09 +0000895 // Now try to reduce the number of global variable initializers in the
896 // module to something small.
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000897 std::unique_ptr<Module> M = CloneModule(OrigM);
Vedant Kumar66e85e62018-02-08 20:27:09 +0000898 bool DeletedInit = false;
Bill Wendling3f833432006-10-25 18:36:14 +0000899
Vedant Kumar66e85e62018-02-08 20:27:09 +0000900 for (GlobalVariable &GV : M->globals()) {
901 if (GV.hasInitializer()) {
902 DeleteGlobalInitializer(&GV);
903 GV.setLinkage(GlobalValue::ExternalLinkage);
904 GV.setComdat(nullptr);
905 DeletedInit = true;
Chris Lattner65e5f652003-04-25 00:53:05 +0000906 }
907 }
Vedant Kumar66e85e62018-02-08 20:27:09 +0000908
909 if (!DeletedInit)
910 return Error::success();
911
912 // See if the program still causes a crash...
913 outs() << "\nChecking to see if we can delete global inits: ";
914
915 if (TestFn(BD, M.get())) { // Still crashes?
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000916 BD.setNewProgram(std::move(M));
Vedant Kumar66e85e62018-02-08 20:27:09 +0000917 outs() << "\n*** Able to remove all global initializers!\n";
918 return Error::success();
919 }
920
921 // No longer crashes.
922 outs() << " - Removing all global inits hides problem!\n";
923
924 std::vector<GlobalVariable *> GVs;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000925 for (GlobalVariable &GV : OrigM.globals())
Vedant Kumar66e85e62018-02-08 20:27:09 +0000926 if (GV.hasInitializer())
927 GVs.push_back(&GV);
928
929 if (GVs.size() > 1 && !BugpointIsInterrupted) {
930 outs() << "\n*** Attempting to reduce the number of global initializers "
931 << "in the testcase\n";
932
933 unsigned OldSize = GVs.size();
934 Expected<bool> Result =
935 ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
936 if (Error E = Result.takeError())
937 return E;
938
939 if (GVs.size() < OldSize)
940 BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
941 }
Justin Bogner1c039152016-09-06 17:18:22 +0000942 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000943}
944
Vedant Kumar08d829d2018-02-08 18:46:49 +0000945static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +0000946 // Attempt to delete instructions using bisection. This should help out nasty
947 // cases with large basic blocks where the problem is at one end.
948 if (!BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +0000949 std::vector<const Instruction *> Insts;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000950 for (const Function &F : BD.getProgram())
Philip Reames1c232f92016-06-29 00:43:18 +0000951 for (const BasicBlock &BB : F)
952 for (const Instruction &I : BB)
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000953 if (!I.isTerminator())
Philip Reames1c232f92016-06-29 00:43:18 +0000954 Insts.push_back(&I);
955
Justin Bogner1c039152016-09-06 17:18:22 +0000956 Expected<bool> Result =
957 ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
958 if (Error E = Result.takeError())
959 return E;
Philip Reames1c232f92016-06-29 00:43:18 +0000960 }
961
962 unsigned Simplification = 2;
963 do {
964 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000965 // TODO: Should we distinguish this with an "interrupted error"?
966 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000967 --Simplification;
968 outs() << "\n*** Attempting to reduce testcase by deleting instruc"
969 << "tions: Simplification Level #" << Simplification << '\n';
970
971 // Now that we have deleted the functions that are unnecessary for the
972 // program, try to remove instructions that are not necessary to cause the
973 // crash. To do this, we loop through all of the instructions in the
974 // remaining functions, deleting them (replacing any values produced with
975 // nulls), and then running ADCE and SimplifyCFG. If the transformed input
976 // still triggers failure, keep deleting until we cannot trigger failure
977 // anymore.
978 //
979 unsigned InstructionsToSkipBeforeDeleting = 0;
980 TryAgain:
981
982 // Loop over all of the (non-terminator) instructions remaining in the
983 // function, attempting to delete them.
984 unsigned CurInstructionNum = 0;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +0000985 for (Module::const_iterator FI = BD.getProgram().begin(),
986 E = BD.getProgram().end();
Justin Bogner8d0a0812016-09-02 01:21:37 +0000987 FI != E; ++FI)
Philip Reames1c232f92016-06-29 00:43:18 +0000988 if (!FI->isDeclaration())
989 for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
990 ++BI)
991 for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
992 I != E; ++I, ++CurInstructionNum) {
993 if (InstructionsToSkipBeforeDeleting) {
994 --InstructionsToSkipBeforeDeleting;
995 } else {
996 if (BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +0000997 // TODO: Should this be some kind of interrupted error?
998 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +0000999
Arnold Schwaighofera8f5a822017-03-07 20:28:59 +00001000 if (I->isEHPad() || I->getType()->isTokenTy() ||
1001 I->isSwiftError())
Philip Reames1c232f92016-06-29 00:43:18 +00001002 continue;
1003
1004 outs() << "Checking instruction: " << *I;
1005 std::unique_ptr<Module> M =
1006 BD.deleteInstructionFromProgram(&*I, Simplification);
1007
1008 // Find out if the pass still crashes on this pass...
1009 if (TestFn(BD, M.get())) {
1010 // Yup, it does, we delete the old module, and continue trying
1011 // to reduce the testcase...
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001012 BD.setNewProgram(std::move(M));
Philip Reames1c232f92016-06-29 00:43:18 +00001013 InstructionsToSkipBeforeDeleting = CurInstructionNum;
Justin Bogner8d0a0812016-09-02 01:21:37 +00001014 goto TryAgain; // I wish I had a multi-level break here!
Philip Reames1c232f92016-06-29 00:43:18 +00001015 }
1016 }
1017 }
1018
1019 if (InstructionsToSkipBeforeDeleting) {
1020 InstructionsToSkipBeforeDeleting = 0;
1021 goto TryAgain;
1022 }
1023
1024 } while (Simplification);
1025 BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
Justin Bogner1c039152016-09-06 17:18:22 +00001026 return Error::success();
Philip Reames1c232f92016-06-29 00:43:18 +00001027}
1028
Philip Reames1c232f92016-06-29 00:43:18 +00001029/// DebugACrash - Given a predicate that determines whether a component crashes
1030/// on a program, try to destructively reduce the program while still keeping
1031/// the predicate true.
Vedant Kumar08d829d2018-02-08 18:46:49 +00001032static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
Philip Reames1c232f92016-06-29 00:43:18 +00001033 // See if we can get away with nuking some of the global variable initializers
1034 // in the program...
1035 if (!NoGlobalRM)
Justin Bogner1c039152016-09-06 17:18:22 +00001036 if (Error E = ReduceGlobalInitializers(BD, TestFn))
1037 return E;
Misha Brukman650ba8e2005-04-22 00:00:37 +00001038
Chris Lattner1d080f22003-04-24 22:24:58 +00001039 // Now try to reduce the number of functions in the module to something small.
Justin Bogner8d0a0812016-09-02 01:21:37 +00001040 std::vector<Function *> Functions;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001041 for (Function &F : BD.getProgram())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001042 if (!F.isDeclaration())
1043 Functions.push_back(&F);
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001044
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001045 if (Functions.size() > 1 && !BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001046 outs() << "\n*** Attempting to reduce the number of functions "
Justin Bogner8d0a0812016-09-02 01:21:37 +00001047 "in the testcase\n";
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001048
Chris Lattner8bda4c42004-02-18 23:26:28 +00001049 unsigned OldSize = Functions.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001050 Expected<bool> Result =
1051 ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
1052 if (Error E = Result.takeError())
1053 return E;
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001054
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001055 if (Functions.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001056 BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001057 }
1058
Daniel Berlin271ca402016-07-27 16:13:25 +00001059 // Attempt to change conditional branches into unconditional branches to
1060 // eliminate blocks.
1061 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001062 std::vector<const BasicBlock *> Blocks;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001063 for (Function &F : BD.getProgram())
Daniel Berlin271ca402016-07-27 16:13:25 +00001064 for (BasicBlock &BB : F)
1065 Blocks.push_back(&BB);
1066 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001067 Expected<bool> Result =
1068 ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
1069 if (Error E = Result.takeError())
1070 return E;
1071 Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
1072 if (Error E = Result.takeError())
1073 return E;
Daniel Berlin271ca402016-07-27 16:13:25 +00001074 if (Blocks.size() < OldSize)
1075 BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
1076 }
1077
Chris Lattnerf32939b2003-04-24 23:51:38 +00001078 // Attempt to delete entire basic blocks at a time to speed up
1079 // convergence... this actually works by setting the terminator of the blocks
1080 // to a return instruction then running simplifycfg, which can potentially
1081 // shrinks the code dramatically quickly
1082 //
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001083 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001084 std::vector<const BasicBlock *> Blocks;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001085 for (Function &F : BD.getProgram())
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +00001086 for (BasicBlock &BB : F)
1087 Blocks.push_back(&BB);
Torok Edwin6ee6f732009-05-24 09:40:47 +00001088 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001089 Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
1090 if (Error E = Result.takeError())
1091 return E;
Torok Edwin6ee6f732009-05-24 09:40:47 +00001092 if (Blocks.size() < OldSize)
Rafael Espindola594994a2010-07-28 18:12:30 +00001093 BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
Chris Lattnerd1e2aae2003-08-05 15:51:05 +00001094 }
Chris Lattnerd4e04742002-12-23 23:49:59 +00001095
Simon Pilgrim0c559f62017-04-14 15:21:15 +00001096 if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
Justin Bogner8d0a0812016-09-02 01:21:37 +00001097 std::vector<const BasicBlock *> Blocks;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001098 for (Function &F : BD.getProgram())
Daniel Berlin60606262016-07-28 22:29:25 +00001099 for (BasicBlock &BB : F)
1100 Blocks.push_back(&BB);
1101 unsigned OldSize = Blocks.size();
Justin Bogner1c039152016-09-06 17:18:22 +00001102 Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
1103 if (Error E = Result.takeError())
1104 return E;
Daniel Berlin60606262016-07-28 22:29:25 +00001105 if (Blocks.size() < OldSize)
1106 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
1107 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001108
Nick Lewycky6e090c92009-05-25 05:30:00 +00001109 // Attempt to delete instructions using bisection. This should help out nasty
1110 // cases with large basic blocks where the problem is at one end.
Philip Reames1c232f92016-06-29 00:43:18 +00001111 if (!BugpointIsInterrupted)
Justin Bogner1c039152016-09-06 17:18:22 +00001112 if (Error E = ReduceInsts(BD, TestFn))
1113 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001114
Michael Ilsemane5428042016-10-25 18:44:13 +00001115 // Attempt to strip debug info metadata.
1116 auto stripMetadata = [&](std::function<bool(Module &)> strip) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001117 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
Michael Ilsemane5428042016-10-25 18:44:13 +00001118 strip(*M);
1119 if (TestFn(BD, M.get()))
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001120 BD.setNewProgram(std::move(M));
Michael Ilsemane5428042016-10-25 18:44:13 +00001121 };
1122 if (!NoStripDebugInfo && !BugpointIsInterrupted) {
1123 outs() << "\n*** Attempting to strip the debug info: ";
1124 stripMetadata(StripDebugInfo);
1125 }
1126 if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
1127 outs() << "\n*** Attempting to strip the debug type info: ";
1128 stripMetadata(stripNonLineTableDebugInfo);
1129 }
1130
Keno Fischer34ca8312015-11-06 00:12:50 +00001131 if (!NoNamedMDRM) {
Keno Fischer34ca8312015-11-06 00:12:50 +00001132 if (!BugpointIsInterrupted) {
1133 // Try to reduce the amount of global metadata (particularly debug info),
1134 // by dropping global named metadata that anchors them
1135 outs() << "\n*** Attempting to remove named metadata: ";
1136 std::vector<std::string> NamedMDNames;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001137 for (auto &NamedMD : BD.getProgram().named_metadata())
Keno Fischer34ca8312015-11-06 00:12:50 +00001138 NamedMDNames.push_back(NamedMD.getName().str());
Justin Bogner1c039152016-09-06 17:18:22 +00001139 Expected<bool> Result =
1140 ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
1141 if (Error E = Result.takeError())
1142 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001143 }
1144
1145 if (!BugpointIsInterrupted) {
1146 // Now that we quickly dropped all the named metadata that doesn't
1147 // contribute to the crash, bisect the operands of the remaining ones
1148 std::vector<const MDNode *> NamedMDOps;
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001149 for (auto &NamedMD : BD.getProgram().named_metadata())
Keno Fischer256df862015-11-06 00:45:47 +00001150 for (auto op : NamedMD.operands())
1151 NamedMDOps.push_back(op);
Justin Bogner1c039152016-09-06 17:18:22 +00001152 Expected<bool> Result =
1153 ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
1154 if (Error E = Result.takeError())
1155 return E;
Keno Fischer34ca8312015-11-06 00:12:50 +00001156 }
Philip Reamesac285cc2016-06-29 00:10:39 +00001157 BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
Keno Fischer34ca8312015-11-06 00:12:50 +00001158 }
1159
Chris Lattner514c02e2003-02-28 16:13:20 +00001160 // Try to clean up the testcase by running funcresolve and globaldce...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001161 if (!BugpointIsInterrupted) {
Dan Gohmanee051522009-07-16 15:30:09 +00001162 outs() << "\n*** Attempting to perform final cleanups: ";
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001163 std::unique_ptr<Module> M = CloneModule(BD.getProgram());
Rafael Espindolab71251c2018-04-24 20:15:27 +00001164 M = BD.performFinalCleanups(std::move(M), true);
Misha Brukman650ba8e2005-04-22 00:00:37 +00001165
Chris Lattnerbeb01fa2005-08-02 02:16:17 +00001166 // Find out if the pass still crashes on the cleaned up program...
Vedant Kumare84e7672018-02-09 05:09:50 +00001167 if (M && TestFn(BD, M.get()))
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001168 BD.setNewProgram(
1169 std::move(M)); // Yup, it does, keep the reduced version...
Chris Lattner514c02e2003-02-28 16:13:20 +00001170 }
1171
Rafael Espindola594994a2010-07-28 18:12:30 +00001172 BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
Chris Lattner514c02e2003-02-28 16:13:20 +00001173
Justin Bogner1c039152016-09-06 17:18:22 +00001174 return Error::success();
Chris Lattner73a6bdd2002-11-20 22:28:10 +00001175}
Brian Gaeke960707c2003-11-11 22:41:34 +00001176
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001177static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001178 return BD.runPasses(*M, BD.getPassesToRun());
Chris Lattner8bda4c42004-02-18 23:26:28 +00001179}
Chris Lattneread1dff2004-02-18 21:02:04 +00001180
Chris Lattner8bda4c42004-02-18 23:26:28 +00001181/// debugOptimizerCrash - This method is called when some pass crashes on input.
1182/// It attempts to prune down the testcase to something reasonable, and figure
1183/// out exactly which pass is crashing.
1184///
Justin Bogner1c039152016-09-06 17:18:22 +00001185Error BugDriver::debugOptimizerCrash(const std::string &ID) {
Dan Gohmanee051522009-07-16 15:30:09 +00001186 outs() << "\n*** Debugging optimizer crash!\n";
Chris Lattner8bda4c42004-02-18 23:26:28 +00001187
1188 // Reduce the list of passes which causes the optimizer to crash...
Justin Bogner1c039152016-09-06 17:18:22 +00001189 if (!BugpointIsInterrupted && !DontReducePassList) {
1190 Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
1191 if (Error E = Result.takeError())
1192 return E;
1193 }
Chris Lattner8bda4c42004-02-18 23:26:28 +00001194
Dan Gohmanee051522009-07-16 15:30:09 +00001195 outs() << "\n*** Found crashing pass"
1196 << (PassesToRun.size() == 1 ? ": " : "es: ")
1197 << getPassesString(PassesToRun) << '\n';
Chris Lattner8bda4c42004-02-18 23:26:28 +00001198
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001199 EmitProgressBitcode(*Program, ID);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001200
Justin Bogner1c039152016-09-06 17:18:22 +00001201 return DebugACrash(*this, TestForOptimizerCrash);
Chris Lattner8bda4c42004-02-18 23:26:28 +00001202}
1203
Rafael Espindolad1c7ef42010-08-05 03:00:22 +00001204static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
Rafael Espindolaf6074ed2018-02-14 21:44:34 +00001205 if (Error E = BD.compileProgram(*M)) {
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001206 if (VerboseErrors)
Justin Bogner1c039152016-09-06 17:18:22 +00001207 errs() << toString(std::move(E)) << "\n";
1208 else {
1209 consumeError(std::move(E));
Sebastian Pop8f7d0192016-07-15 23:15:06 +00001210 errs() << "<crash>\n";
Justin Bogner1c039152016-09-06 17:18:22 +00001211 }
Justin Bogner8d0a0812016-09-02 01:21:37 +00001212 return true; // Tool is still crashing.
Chris Lattner8bda4c42004-02-18 23:26:28 +00001213 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001214 errs() << '\n';
1215 return false;
Chris Lattner8bda4c42004-02-18 23:26:28 +00001216}
Chris Lattneread1dff2004-02-18 21:02:04 +00001217
1218/// debugCodeGeneratorCrash - This method is called when the code generator
1219/// crashes on an input. It attempts to reduce the input as much as possible
1220/// while still causing the code generator to crash.
Justin Bogner1c039152016-09-06 17:18:22 +00001221Error BugDriver::debugCodeGeneratorCrash() {
Dan Gohmand8db3762009-07-15 16:35:29 +00001222 errs() << "*** Debugging code generator crash!\n";
Chris Lattneread1dff2004-02-18 21:02:04 +00001223
Justin Bogner1c039152016-09-06 17:18:22 +00001224 return DebugACrash(*this, TestForCodeGenCrash);
Chris Lattneread1dff2004-02-18 21:02:04 +00001225}