CrashDebugger.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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.getAliaseeObject();
  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(M->getContext());
  311. for (auto A : Attrs)
  312. AB.addAttribute(A);
  313. AttributeList NewAttrs;
  314. NewAttrs = NewAttrs.addFnAttributes(BD.getContext(), AB);
  315. // Set this new list of attributes on the function.
  316. F->setAttributes(NewAttrs);
  317. // If the attribute list includes "optnone" we need to make sure it also
  318. // includes "noinline" otherwise we will get a verifier failure.
  319. if (F->hasFnAttribute(Attribute::OptimizeNone))
  320. F->addFnAttr(Attribute::NoInline);
  321. // Try running on the hacked up program...
  322. if (TestFn(BD, M.get())) {
  323. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  324. // Pass along the set of attributes that caused the crash.
  325. Attrs.clear();
  326. for (Attribute A : NewAttrs.getFnAttrs()) {
  327. Attrs.push_back(A);
  328. }
  329. return true;
  330. }
  331. return false;
  332. }
  333. namespace {
  334. /// Simplify the CFG without completely destroying it.
  335. /// This is not well defined, but basically comes down to "try to eliminate
  336. /// unreachable blocks and constant fold terminators without deciding that
  337. /// certain undefined behavior cuts off the program at the legs".
  338. void simpleSimplifyCfg(Function &F, SmallVectorImpl<BasicBlock *> &BBs) {
  339. if (F.empty())
  340. return;
  341. for (auto *BB : BBs) {
  342. ConstantFoldTerminator(BB);
  343. MergeBlockIntoPredecessor(BB);
  344. }
  345. // Remove unreachable blocks
  346. // removeUnreachableBlocks can't be used here, it will turn various
  347. // undefined behavior into unreachables, but bugpoint was the thing that
  348. // generated the undefined behavior, and we don't want it to kill the entire
  349. // program.
  350. SmallPtrSet<BasicBlock *, 16> Visited;
  351. for (auto *BB : depth_first(&F.getEntryBlock()))
  352. Visited.insert(BB);
  353. SmallVector<BasicBlock *, 16> Unreachable;
  354. for (auto &BB : F)
  355. if (!Visited.count(&BB))
  356. Unreachable.push_back(&BB);
  357. // The dead BB's may be in a dead cycle or otherwise have references to each
  358. // other. Because of this, we have to drop all references first, then delete
  359. // them all at once.
  360. for (auto *BB : Unreachable) {
  361. for (BasicBlock *Successor : successors(&*BB))
  362. if (Visited.count(Successor))
  363. Successor->removePredecessor(&*BB);
  364. BB->dropAllReferences();
  365. }
  366. for (auto *BB : Unreachable)
  367. BB->eraseFromParent();
  368. }
  369. /// ReduceCrashingBlocks reducer - This works by setting the terminators of
  370. /// all terminators except the specified basic blocks to a 'ret' instruction,
  371. /// then running the simplifycfg pass. This has the effect of chopping up
  372. /// the CFG really fast which can reduce large functions quickly.
  373. ///
  374. class ReduceCrashingBlocks : public ListReducer<const BasicBlock *> {
  375. BugDriver &BD;
  376. BugTester TestFn;
  377. public:
  378. ReduceCrashingBlocks(BugDriver &BD, BugTester testFn)
  379. : BD(BD), TestFn(testFn) {}
  380. Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
  381. std::vector<const BasicBlock *> &Kept) override {
  382. if (!Kept.empty() && TestBlocks(Kept))
  383. return KeepSuffix;
  384. if (!Prefix.empty() && TestBlocks(Prefix))
  385. return KeepPrefix;
  386. return NoFailure;
  387. }
  388. bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
  389. };
  390. }
  391. bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock *> &BBs) {
  392. // Clone the program to try hacking it apart...
  393. ValueToValueMapTy VMap;
  394. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  395. // Convert list to set for fast lookup...
  396. SmallPtrSet<BasicBlock *, 8> Blocks;
  397. for (unsigned i = 0, e = BBs.size(); i != e; ++i)
  398. Blocks.insert(cast<BasicBlock>(VMap[BBs[i]]));
  399. outs() << "Checking for crash with only these blocks:";
  400. unsigned NumPrint = Blocks.size();
  401. if (NumPrint > 10)
  402. NumPrint = 10;
  403. for (unsigned i = 0, e = NumPrint; i != e; ++i)
  404. outs() << " " << BBs[i]->getName();
  405. if (NumPrint < Blocks.size())
  406. outs() << "... <" << Blocks.size() << " total>";
  407. outs() << ": ";
  408. // Loop over and delete any hack up any blocks that are not listed...
  409. for (Function &F : M->functions()) {
  410. for (BasicBlock &BB : F) {
  411. if (!Blocks.count(&BB) && BB.getTerminator()->getNumSuccessors()) {
  412. // Loop over all of the successors of this block, deleting any PHI nodes
  413. // that might include it.
  414. for (BasicBlock *Succ : successors(&BB))
  415. Succ->removePredecessor(&BB);
  416. Instruction *BBTerm = BB.getTerminator();
  417. if (BBTerm->isEHPad() || BBTerm->getType()->isTokenTy())
  418. continue;
  419. if (!BBTerm->getType()->isVoidTy())
  420. BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
  421. // Replace the old terminator instruction.
  422. BB.getInstList().pop_back();
  423. new UnreachableInst(BB.getContext(), &BB);
  424. }
  425. }
  426. }
  427. // The CFG Simplifier pass may delete one of the basic blocks we are
  428. // interested in. If it does we need to take the block out of the list. Make
  429. // a "persistent mapping" by turning basic blocks into <function, name> pairs.
  430. // This won't work well if blocks are unnamed, but that is just the risk we
  431. // have to take. FIXME: Can we just name the blocks?
  432. std::vector<std::pair<std::string, std::string>> BlockInfo;
  433. for (BasicBlock *BB : Blocks)
  434. BlockInfo.emplace_back(std::string(BB->getParent()->getName()),
  435. std::string(BB->getName()));
  436. SmallVector<BasicBlock *, 16> ToProcess;
  437. for (auto &F : *M) {
  438. for (auto &BB : F)
  439. if (!Blocks.count(&BB))
  440. ToProcess.push_back(&BB);
  441. simpleSimplifyCfg(F, ToProcess);
  442. ToProcess.clear();
  443. }
  444. // Verify we didn't break anything
  445. std::vector<std::string> Passes;
  446. Passes.push_back("verify");
  447. std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
  448. if (!New) {
  449. errs() << "verify failed!\n";
  450. exit(1);
  451. }
  452. M = std::move(New);
  453. // Try running on the hacked up program...
  454. if (TestFn(BD, M.get())) {
  455. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  456. // Make sure to use basic block pointers that point into the now-current
  457. // module, and that they don't include any deleted blocks.
  458. BBs.clear();
  459. const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
  460. for (const auto &BI : BlockInfo) {
  461. Function *F = cast<Function>(GST.lookup(BI.first));
  462. Value *V = F->getValueSymbolTable()->lookup(BI.second);
  463. if (V && V->getType() == Type::getLabelTy(V->getContext()))
  464. BBs.push_back(cast<BasicBlock>(V));
  465. }
  466. return true;
  467. }
  468. // It didn't crash, try something else.
  469. return false;
  470. }
  471. namespace {
  472. /// ReduceCrashingConditionals reducer - This works by changing
  473. /// conditional branches to unconditional ones, then simplifying the CFG
  474. /// This has the effect of chopping up the CFG really fast which can reduce
  475. /// large functions quickly.
  476. ///
  477. class ReduceCrashingConditionals : public ListReducer<const BasicBlock *> {
  478. BugDriver &BD;
  479. BugTester TestFn;
  480. bool Direction;
  481. public:
  482. ReduceCrashingConditionals(BugDriver &bd, BugTester testFn, bool Direction)
  483. : BD(bd), TestFn(testFn), Direction(Direction) {}
  484. Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
  485. std::vector<const BasicBlock *> &Kept) override {
  486. if (!Kept.empty() && TestBlocks(Kept))
  487. return KeepSuffix;
  488. if (!Prefix.empty() && TestBlocks(Prefix))
  489. return KeepPrefix;
  490. return NoFailure;
  491. }
  492. bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
  493. };
  494. }
  495. bool ReduceCrashingConditionals::TestBlocks(
  496. std::vector<const BasicBlock *> &BBs) {
  497. // Clone the program to try hacking it apart...
  498. ValueToValueMapTy VMap;
  499. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  500. // Convert list to set for fast lookup...
  501. SmallPtrSet<const BasicBlock *, 8> Blocks;
  502. for (const auto *BB : BBs)
  503. Blocks.insert(cast<BasicBlock>(VMap[BB]));
  504. outs() << "Checking for crash with changing conditionals to always jump to "
  505. << (Direction ? "true" : "false") << ":";
  506. unsigned NumPrint = Blocks.size();
  507. if (NumPrint > 10)
  508. NumPrint = 10;
  509. for (unsigned i = 0, e = NumPrint; i != e; ++i)
  510. outs() << " " << BBs[i]->getName();
  511. if (NumPrint < Blocks.size())
  512. outs() << "... <" << Blocks.size() << " total>";
  513. outs() << ": ";
  514. // Loop over and delete any hack up any blocks that are not listed...
  515. for (auto &F : *M)
  516. for (auto &BB : F)
  517. if (!Blocks.count(&BB)) {
  518. auto *BR = dyn_cast<BranchInst>(BB.getTerminator());
  519. if (!BR || !BR->isConditional())
  520. continue;
  521. if (Direction)
  522. BR->setCondition(ConstantInt::getTrue(BR->getContext()));
  523. else
  524. BR->setCondition(ConstantInt::getFalse(BR->getContext()));
  525. }
  526. // The following may destroy some blocks, so we save them first
  527. std::vector<std::pair<std::string, std::string>> BlockInfo;
  528. for (const BasicBlock *BB : Blocks)
  529. BlockInfo.emplace_back(std::string(BB->getParent()->getName()),
  530. std::string(BB->getName()));
  531. SmallVector<BasicBlock *, 16> ToProcess;
  532. for (auto &F : *M) {
  533. for (auto &BB : F)
  534. if (!Blocks.count(&BB))
  535. ToProcess.push_back(&BB);
  536. simpleSimplifyCfg(F, ToProcess);
  537. ToProcess.clear();
  538. }
  539. // Verify we didn't break anything
  540. std::vector<std::string> Passes;
  541. Passes.push_back("verify");
  542. std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
  543. if (!New) {
  544. errs() << "verify failed!\n";
  545. exit(1);
  546. }
  547. M = std::move(New);
  548. // Try running on the hacked up program...
  549. if (TestFn(BD, M.get())) {
  550. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  551. // Make sure to use basic block pointers that point into the now-current
  552. // module, and that they don't include any deleted blocks.
  553. BBs.clear();
  554. const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
  555. for (auto &BI : BlockInfo) {
  556. auto *F = cast<Function>(GST.lookup(BI.first));
  557. Value *V = F->getValueSymbolTable()->lookup(BI.second);
  558. if (V && V->getType() == Type::getLabelTy(V->getContext()))
  559. BBs.push_back(cast<BasicBlock>(V));
  560. }
  561. return true;
  562. }
  563. // It didn't crash, try something else.
  564. return false;
  565. }
  566. namespace {
  567. /// SimplifyCFG reducer - This works by calling SimplifyCFG on each basic block
  568. /// in the program.
  569. class ReduceSimplifyCFG : public ListReducer<const BasicBlock *> {
  570. BugDriver &BD;
  571. BugTester TestFn;
  572. TargetTransformInfo TTI;
  573. public:
  574. ReduceSimplifyCFG(BugDriver &bd, BugTester testFn)
  575. : BD(bd), TestFn(testFn), TTI(bd.getProgram().getDataLayout()) {}
  576. Expected<TestResult> doTest(std::vector<const BasicBlock *> &Prefix,
  577. std::vector<const BasicBlock *> &Kept) override {
  578. if (!Kept.empty() && TestBlocks(Kept))
  579. return KeepSuffix;
  580. if (!Prefix.empty() && TestBlocks(Prefix))
  581. return KeepPrefix;
  582. return NoFailure;
  583. }
  584. bool TestBlocks(std::vector<const BasicBlock *> &Prefix);
  585. };
  586. }
  587. bool ReduceSimplifyCFG::TestBlocks(std::vector<const BasicBlock *> &BBs) {
  588. // Clone the program to try hacking it apart...
  589. ValueToValueMapTy VMap;
  590. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  591. // Convert list to set for fast lookup...
  592. SmallPtrSet<const BasicBlock *, 8> Blocks;
  593. for (const auto *BB : BBs)
  594. Blocks.insert(cast<BasicBlock>(VMap[BB]));
  595. outs() << "Checking for crash with CFG simplifying:";
  596. unsigned NumPrint = Blocks.size();
  597. if (NumPrint > 10)
  598. NumPrint = 10;
  599. for (unsigned i = 0, e = NumPrint; i != e; ++i)
  600. outs() << " " << BBs[i]->getName();
  601. if (NumPrint < Blocks.size())
  602. outs() << "... <" << Blocks.size() << " total>";
  603. outs() << ": ";
  604. // The following may destroy some blocks, so we save them first
  605. std::vector<std::pair<std::string, std::string>> BlockInfo;
  606. for (const BasicBlock *BB : Blocks)
  607. BlockInfo.emplace_back(std::string(BB->getParent()->getName()),
  608. std::string(BB->getName()));
  609. // Loop over and delete any hack up any blocks that are not listed...
  610. for (auto &F : *M)
  611. // Loop over all of the basic blocks and remove them if they are unneeded.
  612. for (Function::iterator BBIt = F.begin(); BBIt != F.end();) {
  613. if (!Blocks.count(&*BBIt)) {
  614. ++BBIt;
  615. continue;
  616. }
  617. simplifyCFG(&*BBIt++, TTI);
  618. }
  619. // Verify we didn't break anything
  620. std::vector<std::string> Passes;
  621. Passes.push_back("verify");
  622. std::unique_ptr<Module> New = BD.runPassesOn(M.get(), Passes);
  623. if (!New) {
  624. errs() << "verify failed!\n";
  625. exit(1);
  626. }
  627. M = std::move(New);
  628. // Try running on the hacked up program...
  629. if (TestFn(BD, M.get())) {
  630. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  631. // Make sure to use basic block pointers that point into the now-current
  632. // module, and that they don't include any deleted blocks.
  633. BBs.clear();
  634. const ValueSymbolTable &GST = BD.getProgram().getValueSymbolTable();
  635. for (auto &BI : BlockInfo) {
  636. auto *F = cast<Function>(GST.lookup(BI.first));
  637. Value *V = F->getValueSymbolTable()->lookup(BI.second);
  638. if (V && V->getType() == Type::getLabelTy(V->getContext()))
  639. BBs.push_back(cast<BasicBlock>(V));
  640. }
  641. return true;
  642. }
  643. // It didn't crash, try something else.
  644. return false;
  645. }
  646. namespace {
  647. /// ReduceCrashingInstructions reducer - This works by removing the specified
  648. /// non-terminator instructions and replacing them with undef.
  649. ///
  650. class ReduceCrashingInstructions : public ListReducer<const Instruction *> {
  651. BugDriver &BD;
  652. BugTester TestFn;
  653. public:
  654. ReduceCrashingInstructions(BugDriver &bd, BugTester testFn)
  655. : BD(bd), TestFn(testFn) {}
  656. Expected<TestResult> doTest(std::vector<const Instruction *> &Prefix,
  657. std::vector<const Instruction *> &Kept) override {
  658. if (!Kept.empty() && TestInsts(Kept))
  659. return KeepSuffix;
  660. if (!Prefix.empty() && TestInsts(Prefix))
  661. return KeepPrefix;
  662. return NoFailure;
  663. }
  664. bool TestInsts(std::vector<const Instruction *> &Prefix);
  665. };
  666. }
  667. bool ReduceCrashingInstructions::TestInsts(
  668. std::vector<const Instruction *> &Insts) {
  669. // Clone the program to try hacking it apart...
  670. ValueToValueMapTy VMap;
  671. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  672. // Convert list to set for fast lookup...
  673. SmallPtrSet<Instruction *, 32> Instructions;
  674. for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
  675. assert(!Insts[i]->isTerminator());
  676. Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
  677. }
  678. outs() << "Checking for crash with only " << Instructions.size();
  679. if (Instructions.size() == 1)
  680. outs() << " instruction: ";
  681. else
  682. outs() << " instructions: ";
  683. for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
  684. for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
  685. for (Instruction &Inst : llvm::make_early_inc_range(*FI)) {
  686. if (!Instructions.count(&Inst) && !Inst.isTerminator() &&
  687. !Inst.isEHPad() && !Inst.getType()->isTokenTy() &&
  688. !Inst.isSwiftError()) {
  689. if (!Inst.getType()->isVoidTy())
  690. Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
  691. Inst.eraseFromParent();
  692. }
  693. }
  694. // Verify that this is still valid.
  695. legacy::PassManager Passes;
  696. Passes.add(createVerifierPass(/*FatalErrors=*/false));
  697. Passes.run(*M);
  698. // Try running on the hacked up program...
  699. if (TestFn(BD, M.get())) {
  700. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  701. // Make sure to use instruction pointers that point into the now-current
  702. // module, and that they don't include any deleted blocks.
  703. Insts.clear();
  704. for (Instruction *Inst : Instructions)
  705. Insts.push_back(Inst);
  706. return true;
  707. }
  708. // It didn't crash, try something else.
  709. return false;
  710. }
  711. namespace {
  712. /// ReduceCrashingMetadata reducer - This works by removing all metadata from
  713. /// the specified instructions.
  714. ///
  715. class ReduceCrashingMetadata : public ListReducer<Instruction *> {
  716. BugDriver &BD;
  717. BugTester TestFn;
  718. public:
  719. ReduceCrashingMetadata(BugDriver &bd, BugTester testFn)
  720. : BD(bd), TestFn(testFn) {}
  721. Expected<TestResult> doTest(std::vector<Instruction *> &Prefix,
  722. std::vector<Instruction *> &Kept) override {
  723. if (!Kept.empty() && TestInsts(Kept))
  724. return KeepSuffix;
  725. if (!Prefix.empty() && TestInsts(Prefix))
  726. return KeepPrefix;
  727. return NoFailure;
  728. }
  729. bool TestInsts(std::vector<Instruction *> &Prefix);
  730. };
  731. } // namespace
  732. bool ReduceCrashingMetadata::TestInsts(std::vector<Instruction *> &Insts) {
  733. // Clone the program to try hacking it apart...
  734. ValueToValueMapTy VMap;
  735. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  736. // Convert list to set for fast lookup...
  737. SmallPtrSet<Instruction *, 32> Instructions;
  738. for (Instruction *I : Insts)
  739. Instructions.insert(cast<Instruction>(VMap[I]));
  740. outs() << "Checking for crash with metadata retained from "
  741. << Instructions.size();
  742. if (Instructions.size() == 1)
  743. outs() << " instruction: ";
  744. else
  745. outs() << " instructions: ";
  746. // Try to drop instruction metadata from all instructions, except the ones
  747. // selected in Instructions.
  748. for (Function &F : *M)
  749. for (Instruction &Inst : instructions(F)) {
  750. if (!Instructions.count(&Inst)) {
  751. Inst.dropUnknownNonDebugMetadata();
  752. Inst.setDebugLoc({});
  753. }
  754. }
  755. // Verify that this is still valid.
  756. legacy::PassManager Passes;
  757. Passes.add(createVerifierPass(/*FatalErrors=*/false));
  758. Passes.run(*M);
  759. // Try running on the hacked up program...
  760. if (TestFn(BD, M.get())) {
  761. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  762. // Make sure to use instruction pointers that point into the now-current
  763. // module, and that they don't include any deleted blocks.
  764. Insts.clear();
  765. for (Instruction *I : Instructions)
  766. Insts.push_back(I);
  767. return true;
  768. }
  769. // It didn't crash, try something else.
  770. return false;
  771. }
  772. namespace {
  773. // Reduce the list of Named Metadata nodes. We keep this as a list of
  774. // names to avoid having to convert back and forth every time.
  775. class ReduceCrashingNamedMD : public ListReducer<std::string> {
  776. BugDriver &BD;
  777. BugTester TestFn;
  778. public:
  779. ReduceCrashingNamedMD(BugDriver &bd, BugTester testFn)
  780. : BD(bd), TestFn(testFn) {}
  781. Expected<TestResult> doTest(std::vector<std::string> &Prefix,
  782. std::vector<std::string> &Kept) override {
  783. if (!Kept.empty() && TestNamedMDs(Kept))
  784. return KeepSuffix;
  785. if (!Prefix.empty() && TestNamedMDs(Prefix))
  786. return KeepPrefix;
  787. return NoFailure;
  788. }
  789. bool TestNamedMDs(std::vector<std::string> &NamedMDs);
  790. };
  791. }
  792. bool ReduceCrashingNamedMD::TestNamedMDs(std::vector<std::string> &NamedMDs) {
  793. ValueToValueMapTy VMap;
  794. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  795. outs() << "Checking for crash with only these named metadata nodes:";
  796. unsigned NumPrint = std::min<size_t>(NamedMDs.size(), 10);
  797. for (unsigned i = 0, e = NumPrint; i != e; ++i)
  798. outs() << " " << NamedMDs[i];
  799. if (NumPrint < NamedMDs.size())
  800. outs() << "... <" << NamedMDs.size() << " total>";
  801. outs() << ": ";
  802. // Make a StringMap for faster lookup
  803. StringSet<> Names;
  804. for (const std::string &Name : NamedMDs)
  805. Names.insert(Name);
  806. // First collect all the metadata to delete in a vector, then
  807. // delete them all at once to avoid invalidating the iterator
  808. std::vector<NamedMDNode *> ToDelete;
  809. ToDelete.reserve(M->named_metadata_size() - Names.size());
  810. for (auto &NamedMD : M->named_metadata())
  811. // Always keep a nonempty llvm.dbg.cu because the Verifier would complain.
  812. if (!Names.count(NamedMD.getName()) &&
  813. (!(NamedMD.getName() == "llvm.dbg.cu" && NamedMD.getNumOperands() > 0)))
  814. ToDelete.push_back(&NamedMD);
  815. for (auto *NamedMD : ToDelete)
  816. NamedMD->eraseFromParent();
  817. // Verify that this is still valid.
  818. legacy::PassManager Passes;
  819. Passes.add(createVerifierPass(/*FatalErrors=*/false));
  820. Passes.run(*M);
  821. // Try running on the hacked up program...
  822. if (TestFn(BD, M.get())) {
  823. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  824. return true;
  825. }
  826. return false;
  827. }
  828. namespace {
  829. // Reduce the list of operands to named metadata nodes
  830. class ReduceCrashingNamedMDOps : public ListReducer<const MDNode *> {
  831. BugDriver &BD;
  832. BugTester TestFn;
  833. public:
  834. ReduceCrashingNamedMDOps(BugDriver &bd, BugTester testFn)
  835. : BD(bd), TestFn(testFn) {}
  836. Expected<TestResult> doTest(std::vector<const MDNode *> &Prefix,
  837. std::vector<const MDNode *> &Kept) override {
  838. if (!Kept.empty() && TestNamedMDOps(Kept))
  839. return KeepSuffix;
  840. if (!Prefix.empty() && TestNamedMDOps(Prefix))
  841. return KeepPrefix;
  842. return NoFailure;
  843. }
  844. bool TestNamedMDOps(std::vector<const MDNode *> &NamedMDOps);
  845. };
  846. }
  847. bool ReduceCrashingNamedMDOps::TestNamedMDOps(
  848. std::vector<const MDNode *> &NamedMDOps) {
  849. // Convert list to set for fast lookup...
  850. SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
  851. for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
  852. OldMDNodeOps.insert(NamedMDOps[i]);
  853. }
  854. outs() << "Checking for crash with only " << OldMDNodeOps.size();
  855. if (OldMDNodeOps.size() == 1)
  856. outs() << " named metadata operand: ";
  857. else
  858. outs() << " named metadata operands: ";
  859. ValueToValueMapTy VMap;
  860. std::unique_ptr<Module> M = CloneModule(BD.getProgram(), VMap);
  861. // This is a little wasteful. In the future it might be good if we could have
  862. // these dropped during cloning.
  863. for (auto &NamedMD : BD.getProgram().named_metadata()) {
  864. // Drop the old one and create a new one
  865. M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
  866. NamedMDNode *NewNamedMDNode =
  867. M->getOrInsertNamedMetadata(NamedMD.getName());
  868. for (MDNode *op : NamedMD.operands())
  869. if (OldMDNodeOps.count(op))
  870. NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
  871. }
  872. // Verify that this is still valid.
  873. legacy::PassManager Passes;
  874. Passes.add(createVerifierPass(/*FatalErrors=*/false));
  875. Passes.run(*M);
  876. // Try running on the hacked up program...
  877. if (TestFn(BD, M.get())) {
  878. // Make sure to use instruction pointers that point into the now-current
  879. // module, and that they don't include any deleted blocks.
  880. NamedMDOps.clear();
  881. for (const MDNode *Node : OldMDNodeOps)
  882. NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));
  883. BD.setNewProgram(std::move(M)); // It crashed, keep the trimmed version...
  884. return true;
  885. }
  886. // It didn't crash, try something else.
  887. return false;
  888. }
  889. /// Attempt to eliminate as many global initializers as possible.
  890. static Error ReduceGlobalInitializers(BugDriver &BD, BugTester TestFn) {
  891. Module &OrigM = BD.getProgram();
  892. if (OrigM.global_empty())
  893. return Error::success();
  894. // Now try to reduce the number of global variable initializers in the
  895. // module to something small.
  896. std::unique_ptr<Module> M = CloneModule(OrigM);
  897. bool DeletedInit = false;
  898. for (GlobalVariable &GV : M->globals()) {
  899. if (GV.hasInitializer()) {
  900. DeleteGlobalInitializer(&GV);
  901. GV.setLinkage(GlobalValue::ExternalLinkage);
  902. GV.setComdat(nullptr);
  903. DeletedInit = true;
  904. }
  905. }
  906. if (!DeletedInit)
  907. return Error::success();
  908. // See if the program still causes a crash...
  909. outs() << "\nChecking to see if we can delete global inits: ";
  910. if (TestFn(BD, M.get())) { // Still crashes?
  911. BD.setNewProgram(std::move(M));
  912. outs() << "\n*** Able to remove all global initializers!\n";
  913. return Error::success();
  914. }
  915. // No longer crashes.
  916. outs() << " - Removing all global inits hides problem!\n";
  917. std::vector<GlobalVariable *> GVs;
  918. for (GlobalVariable &GV : OrigM.globals())
  919. if (GV.hasInitializer())
  920. GVs.push_back(&GV);
  921. if (GVs.size() > 1 && !BugpointIsInterrupted) {
  922. outs() << "\n*** Attempting to reduce the number of global initializers "
  923. << "in the testcase\n";
  924. unsigned OldSize = GVs.size();
  925. Expected<bool> Result =
  926. ReduceCrashingGlobalInitializers(BD, TestFn).reduceList(GVs);
  927. if (Error E = Result.takeError())
  928. return E;
  929. if (GVs.size() < OldSize)
  930. BD.EmitProgressBitcode(BD.getProgram(), "reduced-global-variables");
  931. }
  932. return Error::success();
  933. }
  934. static Error ReduceInsts(BugDriver &BD, BugTester TestFn) {
  935. // Attempt to delete instructions using bisection. This should help out nasty
  936. // cases with large basic blocks where the problem is at one end.
  937. if (!BugpointIsInterrupted) {
  938. std::vector<const Instruction *> Insts;
  939. for (const Function &F : BD.getProgram())
  940. for (const BasicBlock &BB : F)
  941. for (const Instruction &I : BB)
  942. if (!I.isTerminator())
  943. Insts.push_back(&I);
  944. Expected<bool> Result =
  945. ReduceCrashingInstructions(BD, TestFn).reduceList(Insts);
  946. if (Error E = Result.takeError())
  947. return E;
  948. }
  949. unsigned Simplification = 2;
  950. do {
  951. if (BugpointIsInterrupted)
  952. // TODO: Should we distinguish this with an "interrupted error"?
  953. return Error::success();
  954. --Simplification;
  955. outs() << "\n*** Attempting to reduce testcase by deleting instruc"
  956. << "tions: Simplification Level #" << Simplification << '\n';
  957. // Now that we have deleted the functions that are unnecessary for the
  958. // program, try to remove instructions that are not necessary to cause the
  959. // crash. To do this, we loop through all of the instructions in the
  960. // remaining functions, deleting them (replacing any values produced with
  961. // nulls), and then running ADCE and SimplifyCFG. If the transformed input
  962. // still triggers failure, keep deleting until we cannot trigger failure
  963. // anymore.
  964. //
  965. unsigned InstructionsToSkipBeforeDeleting = 0;
  966. TryAgain:
  967. // Loop over all of the (non-terminator) instructions remaining in the
  968. // function, attempting to delete them.
  969. unsigned CurInstructionNum = 0;
  970. for (Module::const_iterator FI = BD.getProgram().begin(),
  971. E = BD.getProgram().end();
  972. FI != E; ++FI)
  973. if (!FI->isDeclaration())
  974. for (Function::const_iterator BI = FI->begin(), E = FI->end(); BI != E;
  975. ++BI)
  976. for (BasicBlock::const_iterator I = BI->begin(), E = --BI->end();
  977. I != E; ++I, ++CurInstructionNum) {
  978. if (InstructionsToSkipBeforeDeleting) {
  979. --InstructionsToSkipBeforeDeleting;
  980. } else {
  981. if (BugpointIsInterrupted)
  982. // TODO: Should this be some kind of interrupted error?
  983. return Error::success();
  984. if (I->isEHPad() || I->getType()->isTokenTy() ||
  985. I->isSwiftError())
  986. continue;
  987. outs() << "Checking instruction: " << *I;
  988. std::unique_ptr<Module> M =
  989. BD.deleteInstructionFromProgram(&*I, Simplification);
  990. // Find out if the pass still crashes on this pass...
  991. if (TestFn(BD, M.get())) {
  992. // Yup, it does, we delete the old module, and continue trying
  993. // to reduce the testcase...
  994. BD.setNewProgram(std::move(M));
  995. InstructionsToSkipBeforeDeleting = CurInstructionNum;
  996. goto TryAgain; // I wish I had a multi-level break here!
  997. }
  998. }
  999. }
  1000. if (InstructionsToSkipBeforeDeleting) {
  1001. InstructionsToSkipBeforeDeleting = 0;
  1002. goto TryAgain;
  1003. }
  1004. } while (Simplification);
  1005. // Attempt to drop metadata from instructions that does not contribute to the
  1006. // crash.
  1007. if (!BugpointIsInterrupted) {
  1008. std::vector<Instruction *> Insts;
  1009. for (Function &F : BD.getProgram())
  1010. for (Instruction &I : instructions(F))
  1011. Insts.push_back(&I);
  1012. Expected<bool> Result =
  1013. ReduceCrashingMetadata(BD, TestFn).reduceList(Insts);
  1014. if (Error E = Result.takeError())
  1015. return E;
  1016. }
  1017. BD.EmitProgressBitcode(BD.getProgram(), "reduced-instructions");
  1018. return Error::success();
  1019. }
  1020. /// DebugACrash - Given a predicate that determines whether a component crashes
  1021. /// on a program, try to destructively reduce the program while still keeping
  1022. /// the predicate true.
  1023. static Error DebugACrash(BugDriver &BD, BugTester TestFn) {
  1024. // See if we can get away with nuking some of the global variable initializers
  1025. // in the program...
  1026. if (!NoGlobalRM)
  1027. if (Error E = ReduceGlobalInitializers(BD, TestFn))
  1028. return E;
  1029. // Now try to reduce the number of functions in the module to something small.
  1030. std::vector<Function *> Functions;
  1031. for (Function &F : BD.getProgram())
  1032. if (!F.isDeclaration())
  1033. Functions.push_back(&F);
  1034. if (Functions.size() > 1 && !BugpointIsInterrupted) {
  1035. outs() << "\n*** Attempting to reduce the number of functions "
  1036. "in the testcase\n";
  1037. unsigned OldSize = Functions.size();
  1038. Expected<bool> Result =
  1039. ReduceCrashingFunctions(BD, TestFn).reduceList(Functions);
  1040. if (Error E = Result.takeError())
  1041. return E;
  1042. if (Functions.size() < OldSize)
  1043. BD.EmitProgressBitcode(BD.getProgram(), "reduced-function");
  1044. }
  1045. if (!NoAttributeRM) {
  1046. // For each remaining function, try to reduce that function's attributes.
  1047. std::vector<std::string> FunctionNames;
  1048. for (Function &F : BD.getProgram())
  1049. FunctionNames.push_back(std::string(F.getName()));
  1050. if (!FunctionNames.empty() && !BugpointIsInterrupted) {
  1051. outs() << "\n*** Attempting to reduce the number of function attributes"
  1052. " in the testcase\n";
  1053. unsigned OldSize = 0;
  1054. unsigned NewSize = 0;
  1055. for (std::string &Name : FunctionNames) {
  1056. Function *Fn = BD.getProgram().getFunction(Name);
  1057. assert(Fn && "Could not find function?");
  1058. std::vector<Attribute> Attrs;
  1059. for (Attribute A : Fn->getAttributes().getFnAttrs())
  1060. Attrs.push_back(A);
  1061. OldSize += Attrs.size();
  1062. Expected<bool> Result =
  1063. ReduceCrashingFunctionAttributes(BD, Name, TestFn).reduceList(Attrs);
  1064. if (Error E = Result.takeError())
  1065. return E;
  1066. NewSize += Attrs.size();
  1067. }
  1068. if (OldSize < NewSize)
  1069. BD.EmitProgressBitcode(BD.getProgram(), "reduced-function-attributes");
  1070. }
  1071. }
  1072. // Attempt to change conditional branches into unconditional branches to
  1073. // eliminate blocks.
  1074. if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
  1075. std::vector<const BasicBlock *> Blocks;
  1076. for (Function &F : BD.getProgram())
  1077. for (BasicBlock &BB : F)
  1078. Blocks.push_back(&BB);
  1079. unsigned OldSize = Blocks.size();
  1080. Expected<bool> Result =
  1081. ReduceCrashingConditionals(BD, TestFn, true).reduceList(Blocks);
  1082. if (Error E = Result.takeError())
  1083. return E;
  1084. Result = ReduceCrashingConditionals(BD, TestFn, false).reduceList(Blocks);
  1085. if (Error E = Result.takeError())
  1086. return E;
  1087. if (Blocks.size() < OldSize)
  1088. BD.EmitProgressBitcode(BD.getProgram(), "reduced-conditionals");
  1089. }
  1090. // Attempt to delete entire basic blocks at a time to speed up
  1091. // convergence... this actually works by setting the terminator of the blocks
  1092. // to a return instruction then running simplifycfg, which can potentially
  1093. // shrinks the code dramatically quickly
  1094. //
  1095. if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
  1096. std::vector<const BasicBlock *> Blocks;
  1097. for (Function &F : BD.getProgram())
  1098. for (BasicBlock &BB : F)
  1099. Blocks.push_back(&BB);
  1100. unsigned OldSize = Blocks.size();
  1101. Expected<bool> Result = ReduceCrashingBlocks(BD, TestFn).reduceList(Blocks);
  1102. if (Error E = Result.takeError())
  1103. return E;
  1104. if (Blocks.size() < OldSize)
  1105. BD.EmitProgressBitcode(BD.getProgram(), "reduced-blocks");
  1106. }
  1107. if (!DisableSimplifyCFG && !BugpointIsInterrupted) {
  1108. std::vector<const BasicBlock *> Blocks;
  1109. for (Function &F : BD.getProgram())
  1110. for (BasicBlock &BB : F)
  1111. Blocks.push_back(&BB);
  1112. unsigned OldSize = Blocks.size();
  1113. Expected<bool> Result = ReduceSimplifyCFG(BD, TestFn).reduceList(Blocks);
  1114. if (Error E = Result.takeError())
  1115. return E;
  1116. if (Blocks.size() < OldSize)
  1117. BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplifycfg");
  1118. }
  1119. // Attempt to delete instructions using bisection. This should help out nasty
  1120. // cases with large basic blocks where the problem is at one end.
  1121. if (!BugpointIsInterrupted)
  1122. if (Error E = ReduceInsts(BD, TestFn))
  1123. return E;
  1124. // Attempt to strip debug info metadata.
  1125. auto stripMetadata = [&](std::function<bool(Module &)> strip) {
  1126. std::unique_ptr<Module> M = CloneModule(BD.getProgram());
  1127. strip(*M);
  1128. if (TestFn(BD, M.get()))
  1129. BD.setNewProgram(std::move(M));
  1130. };
  1131. if (!NoStripDebugInfo && !BugpointIsInterrupted) {
  1132. outs() << "\n*** Attempting to strip the debug info: ";
  1133. stripMetadata(StripDebugInfo);
  1134. }
  1135. if (!NoStripDebugTypeInfo && !BugpointIsInterrupted) {
  1136. outs() << "\n*** Attempting to strip the debug type info: ";
  1137. stripMetadata(stripNonLineTableDebugInfo);
  1138. }
  1139. if (!NoNamedMDRM) {
  1140. if (!BugpointIsInterrupted) {
  1141. // Try to reduce the amount of global metadata (particularly debug info),
  1142. // by dropping global named metadata that anchors them
  1143. outs() << "\n*** Attempting to remove named metadata: ";
  1144. std::vector<std::string> NamedMDNames;
  1145. for (auto &NamedMD : BD.getProgram().named_metadata())
  1146. NamedMDNames.push_back(NamedMD.getName().str());
  1147. Expected<bool> Result =
  1148. ReduceCrashingNamedMD(BD, TestFn).reduceList(NamedMDNames);
  1149. if (Error E = Result.takeError())
  1150. return E;
  1151. }
  1152. if (!BugpointIsInterrupted) {
  1153. // Now that we quickly dropped all the named metadata that doesn't
  1154. // contribute to the crash, bisect the operands of the remaining ones
  1155. std::vector<const MDNode *> NamedMDOps;
  1156. for (auto &NamedMD : BD.getProgram().named_metadata())
  1157. for (auto op : NamedMD.operands())
  1158. NamedMDOps.push_back(op);
  1159. Expected<bool> Result =
  1160. ReduceCrashingNamedMDOps(BD, TestFn).reduceList(NamedMDOps);
  1161. if (Error E = Result.takeError())
  1162. return E;
  1163. }
  1164. BD.EmitProgressBitcode(BD.getProgram(), "reduced-named-md");
  1165. }
  1166. // Try to clean up the testcase by running funcresolve and globaldce...
  1167. if (!BugpointIsInterrupted) {
  1168. outs() << "\n*** Attempting to perform final cleanups: ";
  1169. std::unique_ptr<Module> M = CloneModule(BD.getProgram());
  1170. M = BD.performFinalCleanups(std::move(M), true);
  1171. // Find out if the pass still crashes on the cleaned up program...
  1172. if (M && TestFn(BD, M.get()))
  1173. BD.setNewProgram(
  1174. std::move(M)); // Yup, it does, keep the reduced version...
  1175. }
  1176. BD.EmitProgressBitcode(BD.getProgram(), "reduced-simplified");
  1177. return Error::success();
  1178. }
  1179. static bool TestForOptimizerCrash(const BugDriver &BD, Module *M) {
  1180. return BD.runPasses(*M, BD.getPassesToRun());
  1181. }
  1182. /// debugOptimizerCrash - This method is called when some pass crashes on input.
  1183. /// It attempts to prune down the testcase to something reasonable, and figure
  1184. /// out exactly which pass is crashing.
  1185. ///
  1186. Error BugDriver::debugOptimizerCrash(const std::string &ID) {
  1187. outs() << "\n*** Debugging optimizer crash!\n";
  1188. // Reduce the list of passes which causes the optimizer to crash...
  1189. if (!BugpointIsInterrupted && !DontReducePassList) {
  1190. Expected<bool> Result = ReducePassList(*this).reduceList(PassesToRun);
  1191. if (Error E = Result.takeError())
  1192. return E;
  1193. }
  1194. outs() << "\n*** Found crashing pass"
  1195. << (PassesToRun.size() == 1 ? ": " : "es: ")
  1196. << getPassesString(PassesToRun) << '\n';
  1197. EmitProgressBitcode(*Program, ID);
  1198. auto Res = DebugACrash(*this, TestForOptimizerCrash);
  1199. if (Res || DontReducePassList)
  1200. return Res;
  1201. // Try to reduce the pass list again. This covers additional cases
  1202. // we failed to reduce earlier, because of more complex pass dependencies
  1203. // triggering the crash.
  1204. auto SecondRes = ReducePassList(*this).reduceList(PassesToRun);
  1205. if (Error E = SecondRes.takeError())
  1206. return E;
  1207. outs() << "\n*** Found crashing pass"
  1208. << (PassesToRun.size() == 1 ? ": " : "es: ")
  1209. << getPassesString(PassesToRun) << '\n';
  1210. EmitProgressBitcode(getProgram(), "reduced-simplified");
  1211. return Res;
  1212. }
  1213. static bool TestForCodeGenCrash(const BugDriver &BD, Module *M) {
  1214. if (Error E = BD.compileProgram(*M)) {
  1215. if (VerboseErrors)
  1216. errs() << toString(std::move(E)) << "\n";
  1217. else {
  1218. consumeError(std::move(E));
  1219. errs() << "<crash>\n";
  1220. }
  1221. return true; // Tool is still crashing.
  1222. }
  1223. errs() << '\n';
  1224. return false;
  1225. }
  1226. /// debugCodeGeneratorCrash - This method is called when the code generator
  1227. /// crashes on an input. It attempts to reduce the input as much as possible
  1228. /// while still causing the code generator to crash.
  1229. Error BugDriver::debugCodeGeneratorCrash() {
  1230. errs() << "*** Debugging code generator crash!\n";
  1231. return DebugACrash(*this, TestForCodeGenCrash);
  1232. }