BugDriver.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. //===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===//
  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 class contains all of the shared state and information that is used by
  10. // the BugPoint tool to track down errors in optimizations. This class is the
  11. // main driver class that invokes all sub-functionality.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "BugDriver.h"
  15. #include "ToolRunner.h"
  16. #include "llvm/IR/Module.h"
  17. #include "llvm/IR/Verifier.h"
  18. #include "llvm/IRReader/IRReader.h"
  19. #include "llvm/Linker/Linker.h"
  20. #include "llvm/Pass.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/FileUtilities.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/SourceMgr.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <memory>
  27. using namespace llvm;
  28. namespace llvm {
  29. Triple TargetTriple;
  30. }
  31. DiscardTemp::~DiscardTemp() {
  32. if (SaveTemps) {
  33. if (Error E = File.keep())
  34. errs() << "Failed to keep temp file " << toString(std::move(E)) << '\n';
  35. return;
  36. }
  37. if (Error E = File.discard())
  38. errs() << "Failed to delete temp file " << toString(std::move(E)) << '\n';
  39. }
  40. // Anonymous namespace to define command line options for debugging.
  41. //
  42. namespace {
  43. // Output - The user can specify a file containing the expected output of the
  44. // program. If this filename is set, it is used as the reference diff source,
  45. // otherwise the raw input run through an interpreter is used as the reference
  46. // source.
  47. //
  48. cl::opt<std::string> OutputFile("output",
  49. cl::desc("Specify a reference program output "
  50. "(for miscompilation detection)"));
  51. }
  52. /// If we reduce or update the program somehow, call this method to update
  53. /// bugdriver with it. This deletes the old module and sets the specified one
  54. /// as the current program.
  55. void BugDriver::setNewProgram(std::unique_ptr<Module> M) {
  56. Program = std::move(M);
  57. }
  58. /// getPassesString - Turn a list of passes into a string which indicates the
  59. /// command line options that must be passed to add the passes.
  60. ///
  61. std::string llvm::getPassesString(const std::vector<std::string> &Passes) {
  62. std::string Result;
  63. for (unsigned i = 0, e = Passes.size(); i != e; ++i) {
  64. if (i)
  65. Result += " ";
  66. Result += "-";
  67. Result += Passes[i];
  68. }
  69. return Result;
  70. }
  71. BugDriver::BugDriver(const char *toolname, bool find_bugs, unsigned timeout,
  72. unsigned memlimit, bool use_valgrind, LLVMContext &ctxt)
  73. : Context(ctxt), ToolName(toolname), ReferenceOutputFile(OutputFile),
  74. Program(nullptr), Interpreter(nullptr), SafeInterpreter(nullptr),
  75. cc(nullptr), run_find_bugs(find_bugs), Timeout(timeout),
  76. MemoryLimit(memlimit), UseValgrind(use_valgrind) {}
  77. BugDriver::~BugDriver() {
  78. if (Interpreter != SafeInterpreter)
  79. delete Interpreter;
  80. delete SafeInterpreter;
  81. delete cc;
  82. }
  83. std::unique_ptr<Module> llvm::parseInputFile(StringRef Filename,
  84. LLVMContext &Ctxt) {
  85. SMDiagnostic Err;
  86. std::unique_ptr<Module> Result = parseIRFile(Filename, Err, Ctxt);
  87. if (!Result) {
  88. Err.print("bugpoint", errs());
  89. return Result;
  90. }
  91. if (verifyModule(*Result, &errs())) {
  92. errs() << "bugpoint: " << Filename << ": error: input module is broken!\n";
  93. return std::unique_ptr<Module>();
  94. }
  95. // If we don't have an override triple, use the first one to configure
  96. // bugpoint, or use the host triple if none provided.
  97. if (TargetTriple.getTriple().empty()) {
  98. Triple TheTriple(Result->getTargetTriple());
  99. if (TheTriple.getTriple().empty())
  100. TheTriple.setTriple(sys::getDefaultTargetTriple());
  101. TargetTriple.setTriple(TheTriple.getTriple());
  102. }
  103. Result->setTargetTriple(TargetTriple.getTriple()); // override the triple
  104. return Result;
  105. }
  106. std::unique_ptr<Module> BugDriver::swapProgramIn(std::unique_ptr<Module> M) {
  107. std::unique_ptr<Module> OldProgram = std::move(Program);
  108. Program = std::move(M);
  109. return OldProgram;
  110. }
  111. // This method takes the specified list of LLVM input files, attempts to load
  112. // them, either as assembly or bitcode, then link them together. It returns
  113. // true on failure (if, for example, an input bitcode file could not be
  114. // parsed), and false on success.
  115. //
  116. bool BugDriver::addSources(const std::vector<std::string> &Filenames) {
  117. assert(!Program && "Cannot call addSources multiple times!");
  118. assert(!Filenames.empty() && "Must specify at least on input filename!");
  119. // Load the first input file.
  120. Program = parseInputFile(Filenames[0], Context);
  121. if (!Program)
  122. return true;
  123. outs() << "Read input file : '" << Filenames[0] << "'\n";
  124. for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
  125. std::unique_ptr<Module> M = parseInputFile(Filenames[i], Context);
  126. if (!M.get())
  127. return true;
  128. outs() << "Linking in input file: '" << Filenames[i] << "'\n";
  129. if (Linker::linkModules(*Program, std::move(M)))
  130. return true;
  131. }
  132. outs() << "*** All input ok\n";
  133. // All input files read successfully!
  134. return false;
  135. }
  136. /// run - The top level method that is invoked after all of the instance
  137. /// variables are set up from command line arguments.
  138. ///
  139. Error BugDriver::run() {
  140. if (run_find_bugs) {
  141. // Rearrange the passes and apply them to the program. Repeat this process
  142. // until the user kills the program or we find a bug.
  143. return runManyPasses(PassesToRun);
  144. }
  145. // If we're not running as a child, the first thing that we must do is
  146. // determine what the problem is. Does the optimization series crash the
  147. // compiler, or does it produce illegal code? We make the top-level
  148. // decision by trying to run all of the passes on the input program,
  149. // which should generate a bitcode file. If it does generate a bitcode
  150. // file, then we know the compiler didn't crash, so try to diagnose a
  151. // miscompilation.
  152. if (!PassesToRun.empty()) {
  153. outs() << "Running selected passes on program to test for crash: ";
  154. if (runPasses(*Program, PassesToRun))
  155. return debugOptimizerCrash();
  156. }
  157. // Set up the execution environment, selecting a method to run LLVM bitcode.
  158. if (Error E = initializeExecutionEnvironment())
  159. return E;
  160. // Test to see if we have a code generator crash.
  161. outs() << "Running the code generator to test for a crash: ";
  162. if (Error E = compileProgram(*Program)) {
  163. outs() << toString(std::move(E));
  164. return debugCodeGeneratorCrash();
  165. }
  166. outs() << '\n';
  167. // Run the raw input to see where we are coming from. If a reference output
  168. // was specified, make sure that the raw output matches it. If not, it's a
  169. // problem in the front-end or the code generator.
  170. //
  171. bool CreatedOutput = false;
  172. if (ReferenceOutputFile.empty()) {
  173. outs() << "Generating reference output from raw program: ";
  174. if (Error E = createReferenceFile(*Program)) {
  175. errs() << toString(std::move(E));
  176. return debugCodeGeneratorCrash();
  177. }
  178. CreatedOutput = true;
  179. }
  180. // Make sure the reference output file gets deleted on exit from this
  181. // function, if appropriate.
  182. std::string ROF(ReferenceOutputFile);
  183. FileRemover RemoverInstance(ROF, CreatedOutput && !SaveTemps);
  184. // Diff the output of the raw program against the reference output. If it
  185. // matches, then we assume there is a miscompilation bug and try to
  186. // diagnose it.
  187. outs() << "*** Checking the code generator...\n";
  188. Expected<bool> Diff = diffProgram(*Program, "", "", false);
  189. if (Error E = Diff.takeError()) {
  190. errs() << toString(std::move(E));
  191. return debugCodeGeneratorCrash();
  192. }
  193. if (!*Diff) {
  194. outs() << "\n*** Output matches: Debugging miscompilation!\n";
  195. if (Error E = debugMiscompilation()) {
  196. errs() << toString(std::move(E));
  197. return debugCodeGeneratorCrash();
  198. }
  199. return Error::success();
  200. }
  201. outs() << "\n*** Input program does not match reference diff!\n";
  202. outs() << "Debugging code generator problem!\n";
  203. if (Error E = debugCodeGenerator()) {
  204. errs() << toString(std::move(E));
  205. return debugCodeGeneratorCrash();
  206. }
  207. return Error::success();
  208. }
  209. void llvm::PrintFunctionList(const std::vector<Function *> &Funcs) {
  210. unsigned NumPrint = Funcs.size();
  211. if (NumPrint > 10)
  212. NumPrint = 10;
  213. for (unsigned i = 0; i != NumPrint; ++i)
  214. outs() << " " << Funcs[i]->getName();
  215. if (NumPrint < Funcs.size())
  216. outs() << "... <" << Funcs.size() << " total>";
  217. outs().flush();
  218. }
  219. void llvm::PrintGlobalVariableList(const std::vector<GlobalVariable *> &GVs) {
  220. unsigned NumPrint = GVs.size();
  221. if (NumPrint > 10)
  222. NumPrint = 10;
  223. for (unsigned i = 0; i != NumPrint; ++i)
  224. outs() << " " << GVs[i]->getName();
  225. if (NumPrint < GVs.size())
  226. outs() << "... <" << GVs.size() << " total>";
  227. outs().flush();
  228. }