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