CrashDebugger.cpp 49 KB

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