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