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