blob: 4c184d64a6392a6a9bb17cfc861a75f0e1721891 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
Chris Lattnera57d86b2004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattner4a106452002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner126840f2003-04-24 20:16:29 +000016#include "ListReducer.h"
Daniel Dunbarca740962009-08-18 03:35:57 +000017#include "ToolRunner.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000021#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000022#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000023#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000024#include "llvm/Analysis/Verifier.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000025#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chris Lattner59615f02005-01-15 00:07:19 +000028#include "llvm/Config/config.h" // for HAVE_LINK_R
Chris Lattnerfa761832004-01-14 03:38:37 +000029using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000030
Chris Lattnera57d86b2004-04-05 22:58:16 +000031namespace llvm {
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +000032 extern cl::opt<std::string> OutputPrefix;
Chris Lattnera57d86b2004-04-05 22:58:16 +000033 extern cl::list<std::string> InputArgv;
34}
35
Chris Lattnerefdc0b52004-03-14 20:50:42 +000036namespace {
Reid Spencerdc31a8a2006-11-11 19:05:02 +000037 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
40 cl::init(false));
David Goodwin265d82e2009-07-28 23:08:36 +000041 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
44 cl::init(false));
Reid Spencerdc31a8a2006-11-11 19:05:02 +000045
Chris Lattnerfa761832004-01-14 03:38:37 +000046 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
47 BugDriver &BD;
48 public:
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000050
Chris Lattnerfa761832004-01-14 03:38:37 +000051 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
52 std::vector<const PassInfo*> &Suffix);
53 };
54}
Chris Lattner640f22e2003-04-24 17:02:17 +000055
Misha Brukman8c194ea2004-04-21 18:36:43 +000056/// TestResult - After passes have been split into a test group and a control
57/// group, see if they still break the program.
58///
Chris Lattner640f22e2003-04-24 17:02:17 +000059ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000060ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000061 std::vector<const PassInfo*> &Suffix) {
62 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000063 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000064 outs() << "Checking to see if '" << getPassesString(Suffix)
65 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000066
Gabor Greif8ff70c22007-07-04 21:55:50 +000067 std::string BitcodeResult;
68 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000069 errs() << " Error running this sequence of passes"
70 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000071 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +000072 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000073 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000074 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000075
Chris Lattner640f22e2003-04-24 17:02:17 +000076 // Check to see if the finished program matches the reference output...
Gabor Greif8ff70c22007-07-04 21:55:50 +000077 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000078 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000079 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000080 errs() << BD.getToolName() << ": I'm confused: the test fails when "
81 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000082 exit(1);
83 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000084 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000085 }
Dan Gohmanac95cc72009-07-16 15:30:09 +000086 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000087
88 if (Prefix.empty()) return NoFailure;
89
Chris Lattner06943ad2003-04-25 03:16:05 +000090 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000091 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000092 outs() << "Checking to see if '" << getPassesString(Prefix)
93 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000094
95 // If it is not broken with the kept passes, it's possible that the prefix
96 // passes must be run before the kept passes to break it. If the program
97 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif8ff70c22007-07-04 21:55:50 +000098 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +000099 // prefix passes, then discard the prefix passes.
100 //
Gabor Greif8ff70c22007-07-04 21:55:50 +0000101 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000102 errs() << " Error running this sequence of passes"
103 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000104 BD.setPassesToRun(Prefix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000105 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000106 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000107 }
108
109 // If the prefix maintains the predicate by itself, only keep the prefix!
Gabor Greif8ff70c22007-07-04 21:55:50 +0000110 if (BD.diffProgram(BitcodeResult)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000111 outs() << " nope.\n";
Gabor Greif8ff70c22007-07-04 21:55:50 +0000112 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000113 return KeepPrefix;
114 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000115 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000116
117 // Ok, so now we know that the prefix passes work, try running the suffix
118 // passes on the result of the prefix passes.
119 //
Owen Anderson8b477ed2009-07-01 16:58:40 +0000120 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
Chris Lattner640f22e2003-04-24 17:02:17 +0000121 if (PrefixOutput == 0) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000122 errs() << BD.getToolName() << ": Error reading bitcode file '"
123 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000124 exit(1);
125 }
Gabor Greif8ff70c22007-07-04 21:55:50 +0000126 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000127
128 // Don't check if there are no passes in the suffix.
129 if (Suffix.empty())
130 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000131
Dan Gohmanac95cc72009-07-16 15:30:09 +0000132 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000133 << "' passes compile correctly after the '"
134 << getPassesString(Prefix) << "' passes: ";
135
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000136 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000137 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000138 errs() << " Error running this sequence of passes"
139 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000140 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000141 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000142 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 }
144
145 // Run the result...
Gabor Greif8ff70c22007-07-04 21:55:50 +0000146 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000147 outs() << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000148 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000149 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000150 }
151
152 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000153 outs() << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000154 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000155 return NoFailure;
156}
157
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000158namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000159 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
160 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000161 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000162 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000163 ReduceMiscompilingFunctions(BugDriver &bd,
164 bool (*F)(BugDriver &, Module *, Module *))
165 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000166
Chris Lattnerfa761832004-01-14 03:38:37 +0000167 virtual TestResult doTest(std::vector<Function*> &Prefix,
168 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000169 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000170 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000171 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000172 return KeepPrefix;
173 return NoFailure;
174 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000175
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000176 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000177 };
178}
Chris Lattner640f22e2003-04-24 17:02:17 +0000179
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000180/// TestMergedProgram - Given two modules, link them together and run the
181/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000182/// matches, return false, otherwise return true. If the DeleteInputs argument
183/// is set to true then this function deletes both input modules before it
184/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000185///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000186static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
187 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000188 // Link the two portions of the program back to together.
189 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000190 if (!DeleteInputs) {
191 M1 = CloneModule(M1);
192 M2 = CloneModule(M2);
193 }
Reid Spencere4874022004-12-13 03:01:03 +0000194 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000195 errs() << BD.getToolName() << ": Error linking modules together:"
196 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000197 exit(1);
198 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000199 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000200
201 Module *OldProgram = BD.swapProgramIn(M1);
202
203 // Execute the program. If it does not match the expected output, we must
204 // return true.
205 bool Broken = BD.diffProgram();
206
207 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000208 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000209 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000210 return Broken;
211}
212
Misha Brukman8c194ea2004-04-21 18:36:43 +0000213/// TestFuncs - split functions in a Module into two groups: those that are
214/// under consideration for miscompilation vs. those that are not, and test
215/// accordingly. Each group of functions becomes a separate Module.
216///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000217bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000218 // Test to see if the function is misoptimized if we ONLY run it on the
219 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000220 outs() << "Checking to see if the program is misoptimized when "
221 << (Funcs.size()==1 ? "this function is" : "these functions are")
222 << " run through the pass"
223 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000224 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000225 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000226
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000227 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000228 DenseMap<const Value*, Value*> ValueMap;
229 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
230 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
231 ValueMap);
Chris Lattner640f22e2003-04-24 17:02:17 +0000232
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000233 // Run the predicate, note that the predicate will delete both input modules.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000234 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000235}
236
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000237/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000238///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000239static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner67ef9e42006-05-04 23:35:31 +0000240 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner9d5511b2009-07-15 04:50:47 +0000241 I != E; ++I) {
242 // Don't mangle asm names.
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000243 if (!I->hasName())
244 I->setName("anon_global");
Chris Lattner9d5511b2009-07-15 04:50:47 +0000245 }
246 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000247 if (!I->hasName())
248 I->setName("anon_fn");
Chris Lattner9d5511b2009-07-15 04:50:47 +0000249 }
Chris Lattner36ee07f2004-04-11 23:52:35 +0000250}
251
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000252/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
253/// check to see if we can extract the loops in the region without obscuring the
254/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000255///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000256static bool ExtractLoops(BugDriver &BD,
257 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000258 std::vector<Function*> &MiscompiledFunctions) {
259 bool MadeChange = false;
260 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000261 if (BugpointIsInterrupted) return MadeChange;
262
Dan Gohmand50330c2009-04-22 15:57:18 +0000263 DenseMap<const Value*, Value*> ValueMap;
264 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000265 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000266 MiscompiledFunctions,
267 ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000268 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
269 if (!ToOptimizeLoopExtracted) {
270 // If the loop extractor crashed or if there were no extractible loops,
271 // then this chapter of our odyssey is over with.
272 delete ToNotOptimize;
273 delete ToOptimize;
274 return MadeChange;
275 }
276
Dan Gohman65f57c22009-07-15 16:35:29 +0000277 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000278
279 // Bugpoint is intentionally not very trusting of LLVM transformations. In
280 // particular, we're not going to assume that the loop extractor works, so
281 // we're going to test the newly loop extracted program to make sure nothing
282 // has broken. If something broke, then we'll inform the user and stop
283 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000284 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000285 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000286 BD.switchToInterpreter(AI);
287
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000288 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000289 errs() << " *** ERROR: Loop extraction broke the program. :("
290 << " Please report a bug!\n";
291 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000292
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000293 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
294 ToNotOptimize);
295 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
296 ToOptimize);
297 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Chris Lattner56c41862005-05-08 21:54:56 +0000298 ToOptimizeLoopExtracted);
299
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000300 errs() << "Please submit the "
301 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000302 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000303 delete ToNotOptimize;
304 delete ToOptimizeLoopExtracted;
305 return MadeChange;
306 }
Chris Lattner56c41862005-05-08 21:54:56 +0000307 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000308 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000309
Dan Gohmanac95cc72009-07-16 15:30:09 +0000310 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000311 // Clone modules, the tester function will free them.
312 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
313 Module *TNOBackup = CloneModule(ToNotOptimize);
314 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000315 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000316 // If the program is not still broken, then loop extraction did something
317 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000318 delete TOLEBackup;
319 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000320 return MadeChange;
321 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000322 ToOptimizeLoopExtracted = TOLEBackup;
323 ToNotOptimize = TNOBackup;
324
Dan Gohmanac95cc72009-07-16 15:30:09 +0000325 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000326
Chris Lattner90c18c52004-11-16 06:31:38 +0000327 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
328 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
329 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000330 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000331 MisCompFunctions.push_back(std::make_pair(I->getName(),
332 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000333
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000334 // Okay, great! Now we know that we extracted a loop and that loop
335 // extraction both didn't break the program, and didn't mask the problem.
336 // Replace the current program with the loop extracted version, and try to
337 // extract another loop.
338 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000339 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohman65f57c22009-07-15 16:35:29 +0000340 errs() << BD.getToolName() << ": Error linking modules together:"
341 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000342 exit(1);
343 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000344 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000345
346 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000347 // module. Update this list to include all of the functions in the
348 // optimized and loop extracted module.
349 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000350 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000351 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
352
Chris Lattner90c18c52004-11-16 06:31:38 +0000353 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000354 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
355 "found wrong function type?");
Chris Lattner90c18c52004-11-16 06:31:38 +0000356 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000357 }
358
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000359 BD.setNewProgram(ToNotOptimize);
360 MadeChange = true;
361 }
362}
363
Chris Lattner5e783ab2004-05-11 21:54:13 +0000364namespace {
365 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
366 BugDriver &BD;
367 bool (*TestFn)(BugDriver &, Module *, Module *);
368 std::vector<Function*> FunctionsBeingTested;
369 public:
370 ReduceMiscompiledBlocks(BugDriver &bd,
371 bool (*F)(BugDriver &, Module *, Module *),
372 const std::vector<Function*> &Fns)
373 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000374
Chris Lattner5e783ab2004-05-11 21:54:13 +0000375 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
376 std::vector<BasicBlock*> &Suffix) {
377 if (!Suffix.empty() && TestFuncs(Suffix))
378 return KeepSuffix;
379 if (TestFuncs(Prefix))
380 return KeepPrefix;
381 return NoFailure;
382 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000383
Chris Lattner5e783ab2004-05-11 21:54:13 +0000384 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
385 };
386}
387
388/// TestFuncs - Extract all blocks for the miscompiled functions except for the
389/// specified blocks. If the problem still exists, return true.
390///
391bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
392 // Test to see if the function is misoptimized if we ONLY run it on the
393 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000394 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000395 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000396 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000397 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000398 outs() << BBs[i]->getName() << " ";
399 if (BBs.size() > 10) outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000400 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000401 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000402 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000403 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000404
405 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000406 DenseMap<const Value*, Value*> ValueMap;
407 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000408 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000409 FunctionsBeingTested,
410 ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000411
412 // Try the extraction. If it doesn't work, then the block extractor crashed
413 // or something, in which case bugpoint can't chase down this possibility.
414 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
415 delete ToOptimize;
416 // Run the predicate, not that the predicate will delete both input modules.
417 return TestFn(BD, New, ToNotOptimize);
418 }
419 delete ToOptimize;
420 delete ToNotOptimize;
421 return false;
422}
423
424
425/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
426/// extract as many basic blocks from the region as possible without obscuring
427/// the bug.
428///
429static bool ExtractBlocks(BugDriver &BD,
430 bool (*TestFn)(BugDriver &, Module *, Module *),
431 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000432 if (BugpointIsInterrupted) return false;
433
Chris Lattner5e783ab2004-05-11 21:54:13 +0000434 std::vector<BasicBlock*> Blocks;
435 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
436 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
437 E = MiscompiledFunctions[i]->end(); I != E; ++I)
438 Blocks.push_back(I);
439
440 // Use the list reducer to identify blocks that can be extracted without
441 // obscuring the bug. The Blocks list will end up containing blocks that must
442 // be retained from the original program.
443 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000444
445 // Check to see if all blocks are extractible first.
446 if (ReduceMiscompiledBlocks(BD, TestFn,
447 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
448 Blocks.clear();
449 } else {
450 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
451 if (Blocks.size() == OldSize)
452 return false;
453 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000454
Dan Gohmand50330c2009-04-22 15:57:18 +0000455 DenseMap<const Value*, Value*> ValueMap;
456 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000457 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohmand50330c2009-04-22 15:57:18 +0000458 MiscompiledFunctions,
459 ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000460 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
461 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000462 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000463 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000464 delete ProgClone;
465 delete ToExtract;
466 return false;
467 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000468
Chris Lattner2290e752004-05-12 02:43:24 +0000469 // Otherwise, block extraction succeeded. Link the two program fragments back
470 // together.
471 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000472
Chris Lattner90c18c52004-11-16 06:31:38 +0000473 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
474 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
475 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000476 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000477 MisCompFunctions.push_back(std::make_pair(I->getName(),
478 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000479
Chris Lattner2290e752004-05-12 02:43:24 +0000480 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000481 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000482 errs() << BD.getToolName() << ": Error linking modules together:"
483 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000484 exit(1);
485 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000486 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000487
Chris Lattner2290e752004-05-12 02:43:24 +0000488 // Set the new program and delete the old one.
489 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000490
Chris Lattner2290e752004-05-12 02:43:24 +0000491 // Update the list of miscompiled functions.
492 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000493
Chris Lattner90c18c52004-11-16 06:31:38 +0000494 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000495 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000496 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000497 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
498 "Function has wrong type??");
Chris Lattner90c18c52004-11-16 06:31:38 +0000499 MiscompiledFunctions.push_back(NewF);
500 }
Chris Lattner2290e752004-05-12 02:43:24 +0000501
502 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000503}
504
505
Chris Lattnerb15825b2004-04-05 21:37:38 +0000506/// DebugAMiscompilation - This is a generic driver to narrow down
507/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000508///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000509static std::vector<Function*>
510DebugAMiscompilation(BugDriver &BD,
511 bool (*TestFn)(BugDriver &, Module *, Module *)) {
512 // Okay, now that we have reduced the list of passes which are causing the
513 // failure, see if we can pin down which functions are being
514 // miscompiled... first build a list of all of the non-external functions in
515 // the program.
516 std::vector<Function*> MiscompiledFunctions;
517 Module *Prog = BD.getProgram();
518 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000519 if (!I->isDeclaration())
Chris Lattnerb15825b2004-04-05 21:37:38 +0000520 MiscompiledFunctions.push_back(I);
521
522 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000523 if (!BugpointIsInterrupted)
524 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000525
Dan Gohmanac95cc72009-07-16 15:30:09 +0000526 outs() << "\n*** The following function"
527 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
528 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000529 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000530 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000531
532 // See if we can rip any loops out of the miscompiled functions and still
533 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000534
Reid Spencer2803b4c2006-11-11 19:59:25 +0000535 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
536 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000537 // Okay, we extracted some loops and the problem still appears. See if we
538 // can eliminate some of the created functions from being candidates.
Chris Lattner36ee07f2004-04-11 23:52:35 +0000539 DisambiguateGlobalSymbols(BD.getProgram());
540
Chris Lattnerb15825b2004-04-05 21:37:38 +0000541 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000542 if (!BugpointIsInterrupted)
543 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000544
Dan Gohmanac95cc72009-07-16 15:30:09 +0000545 outs() << "\n*** The following function"
546 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
547 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000548 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000549 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000550 }
551
David Goodwin265d82e2009-07-28 23:08:36 +0000552 if (!BugpointIsInterrupted && !DisableBlockExtraction &&
Chris Lattneraed98fa2005-08-02 23:25:56 +0000553 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000554 // Okay, we extracted some blocks and the problem still appears. See if we
555 // can eliminate some of the created functions from being candidates.
Chris Lattner5e783ab2004-05-11 21:54:13 +0000556 DisambiguateGlobalSymbols(BD.getProgram());
557
558 // Do the reduction...
559 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000560
Dan Gohmanac95cc72009-07-16 15:30:09 +0000561 outs() << "\n*** The following function"
562 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
563 << " being miscompiled: ";
Chris Lattner5e783ab2004-05-11 21:54:13 +0000564 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000565 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000566 }
567
Chris Lattnerb15825b2004-04-05 21:37:38 +0000568 return MiscompiledFunctions;
569}
570
Chris Lattnera57d86b2004-04-05 22:58:16 +0000571/// TestOptimizer - This is the predicate function used to check to see if the
572/// "Test" portion of the program is misoptimized. If so, return true. In any
573/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000574///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000575static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
576 // Run the optimization passes on ToOptimize, producing a transformed version
577 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000578 outs() << " Optimizing functions being tested: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000579 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
580 /*AutoDebugCrashes*/true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000581 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000582 delete Test;
583
Dan Gohmanac95cc72009-07-16 15:30:09 +0000584 outs() << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000585 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000586 outs() << (Broken ? " nope.\n" : " yup.\n");
Chris Lattnerb15825b2004-04-05 21:37:38 +0000587 return Broken;
588}
589
590
Chris Lattner4a106452002-12-23 23:50:16 +0000591/// debugMiscompilation - This method is used when the passes selected are not
592/// crashing, but the generated output is semantically different from the
593/// input.
594///
595bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000596 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000597 if (!BugpointIsInterrupted)
598 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000599 errs() << "*** Optimized program matches reference output! No problem"
600 << " detected...\nbugpoint can't help you with your problem!\n";
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000601 return false;
602 }
Chris Lattner4a106452002-12-23 23:50:16 +0000603
Dan Gohmanac95cc72009-07-16 15:30:09 +0000604 outs() << "\n*** Found miscompiling pass"
605 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
606 << getPassesString(getPassesToRun()) << '\n';
Gabor Greif8ff70c22007-07-04 21:55:50 +0000607 EmitProgressBitcode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000608
Chris Lattnerb15825b2004-04-05 21:37:38 +0000609 std::vector<Function*> MiscompiledFunctions =
610 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000611
Gabor Greif8ff70c22007-07-04 21:55:50 +0000612 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000613 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohmand50330c2009-04-22 15:57:18 +0000614 DenseMap<const Value*, Value*> ValueMap;
615 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000616 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000617 MiscompiledFunctions,
618 ValueMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000619
Dan Gohmanac95cc72009-07-16 15:30:09 +0000620 outs() << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000621 ToNotOptimize = swapProgramIn(ToNotOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000622 EmitProgressBitcode("tonotoptimize", true);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000623 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000624
Dan Gohmanac95cc72009-07-16 15:30:09 +0000625 outs() << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000626 ToOptimize = swapProgramIn(ToOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000627 EmitProgressBitcode("tooptimize");
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000628 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000629
Chris Lattner4a106452002-12-23 23:50:16 +0000630 return false;
631}
Brian Gaeked0fde302003-11-11 22:41:34 +0000632
Chris Lattnera57d86b2004-04-05 22:58:16 +0000633/// CleanupAndPrepareModules - Get the specified modules ready for code
634/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000635///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000636static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
637 Module *Safe) {
638 // Clean up the modules, removing extra cruft that we don't need anymore...
639 Test = BD.performFinalCleanups(Test);
640
641 // If we are executing the JIT, we have several nasty issues to take care of.
642 if (!BD.isExecutingJIT()) return;
643
644 // First, if the main function is in the Safe module, we must add a stub to
645 // the Test module to call into it. Thus, we create a new function `main'
646 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000647 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000648 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000649 // Rename it
650 oldMain->setName("llvm_bugpoint_old_main");
651 // Create a NEW `main' function with same type in the test module.
Gabor Greif051a9502008-04-06 20:25:17 +0000652 Function *newMain = Function::Create(oldMain->getFunctionType(),
653 GlobalValue::ExternalLinkage,
654 "main", Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000655 // Create an `oldmain' prototype in the test module, which will
656 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000657 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
658 GlobalValue::ExternalLinkage,
659 oldMain->getName(), Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000660 // Set up and remember the argument list for the main function.
661 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000662 for (Function::arg_iterator
663 I = newMain->arg_begin(), E = newMain->arg_end(),
664 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000665 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnera57d86b2004-04-05 22:58:16 +0000666 args.push_back(I);
667 }
668
669 // Call the old main function and return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000670 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Gabor Greif051a9502008-04-06 20:25:17 +0000671 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
672 "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000673
Chris Lattnera57d86b2004-04-05 22:58:16 +0000674 // If the type of old function wasn't void, return value of call
Owen Anderson1d0be152009-08-13 21:58:54 +0000675 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000676 }
677
678 // The second nasty issue we must deal with in the JIT is that the Safe
679 // module cannot directly reference any functions defined in the test
680 // module. Instead, we use a JIT API call to dynamically resolve the
681 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000682
Chris Lattnera57d86b2004-04-05 22:58:16 +0000683 // Add the resolver to the Safe module.
684 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner2db43c82007-01-07 08:13:39 +0000685 Constant *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000686 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000687 Type::getInt8PtrTy(Safe->getContext()),
688 Type::getInt8PtrTy(Safe->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +0000689 (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000690
Chris Lattnera57d86b2004-04-05 22:58:16 +0000691 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000692 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000693 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000694 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000695 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000696
697 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000698 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000699 // 1. Add a string constant with its name to the global file
Owen Anderson1d0be152009-08-13 21:58:54 +0000700 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000701 GlobalVariable *funcName =
Owen Andersone9b11b42009-07-08 19:03:57 +0000702 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000703 GlobalValue::InternalLinkage, InitArray,
Owen Andersone9b11b42009-07-08 19:03:57 +0000704 F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000705
706 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
707 // sbyte* so it matches the signature of the resolver function.
708
709 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson1d0be152009-08-13 21:58:54 +0000710 std::vector<Constant*> GEPargs(2,
711 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000712 Value *GEP =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000713 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000714 std::vector<Value*> ResolverArgs;
715 ResolverArgs.push_back(GEP);
716
Misha Brukmande4803d2004-04-19 03:36:47 +0000717 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
718 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000719 if (!F->use_empty()) {
720 // Create a new global to hold the cached function pointer.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000721 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattnera3efca12005-07-12 01:00:32 +0000722 GlobalVariable *Cache =
Owen Andersone9b11b42009-07-08 19:03:57 +0000723 new GlobalVariable(*F->getParent(), F->getType(),
724 false, GlobalValue::InternalLinkage,
725 NullPtr,F->getName()+".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000726
Misha Brukmande4803d2004-04-19 03:36:47 +0000727 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000728 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greif051a9502008-04-06 20:25:17 +0000729 Function *FuncWrapper = Function::Create(FuncTy,
730 GlobalValue::InternalLinkage,
731 F->getName() + "_wrapper",
732 F->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000733 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
734 "entry", FuncWrapper);
735 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
736 "usecache", FuncWrapper);
737 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
738 "lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000739
Chris Lattnera3efca12005-07-12 01:00:32 +0000740 // Check to see if we already looked up the value.
741 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000742 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
743 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000744 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000745
Misha Brukmande4803d2004-04-19 03:36:47 +0000746 // Resolve the call to function F via the JIT API:
747 //
748 // call resolver(GetElementPtr...)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000749 CallInst *Resolver =
750 CallInst::Create(resolverFunc, ResolverArgs.begin(),
751 ResolverArgs.end(), "resolver", LookupBB);
752
753 // Cast the result from the resolver to correctly-typed function.
754 CastInst *CastedResolver =
755 new BitCastInst(Resolver,
Owen Andersondebcb012009-07-29 22:17:13 +0000756 PointerType::getUnqual(F->getFunctionType()),
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000757 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000758
Chris Lattnera3efca12005-07-12 01:00:32 +0000759 // Save the value in our cache.
760 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000761 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000762
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000763 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
764 "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000765 FuncPtr->addIncoming(CastedResolver, LookupBB);
766 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000767
Chris Lattnera3efca12005-07-12 01:00:32 +0000768 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000769 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000770 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
771 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000772 Args.push_back(i);
773
774 // Pass on the arguments to the real function, return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000775 if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
Gabor Greif051a9502008-04-06 20:25:17 +0000776 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000777 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000778 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000779 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
780 "retval", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000781 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000782 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000783
Misha Brukmande4803d2004-04-19 03:36:47 +0000784 // Use the wrapper function instead of the old function
785 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000786 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000787 }
788 }
789 }
790
791 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000792 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000793 abort();
794 }
795}
796
797
798
799/// TestCodeGenerator - This is the predicate function used to check to see if
800/// the "Test" portion of the program is miscompiled by the code generator under
801/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000802///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000803static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
804 CleanupAndPrepareModules(BD, Test, Safe);
805
Reid Spencer97182982004-12-15 01:53:08 +0000806 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000807 std::string ErrMsg;
808 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000809 errs() << BD.getToolName() << "Error making unique filename: "
810 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000811 exit(1);
812 }
Chris Lattner74382b72009-08-23 22:45:37 +0000813 if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
814 errs() << "Error writing bitcode to `" << TestModuleBC.str()
815 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000816 exit(1);
817 }
818 delete Test;
819
820 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000821 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000822 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000823 errs() << BD.getToolName() << "Error making unique filename: "
824 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000825 exit(1);
826 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000827
Chris Lattner74382b72009-08-23 22:45:37 +0000828 if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
829 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
830 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000831 exit(1);
832 }
Chris Lattner74382b72009-08-23 22:45:37 +0000833 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000834 delete Safe;
835
836 // Run the code generator on the `Test' code, loading the shared library.
837 // The function returns whether or not the new output differs from reference.
Chris Lattner74382b72009-08-23 22:45:37 +0000838 int Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000839
840 if (Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000841 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000842 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000843 errs() << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000844 TestModuleBC.eraseFromDisk();
845 SafeModuleBC.eraseFromDisk();
846 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000847
848 return Result;
849}
850
851
Misha Brukman8c194ea2004-04-21 18:36:43 +0000852/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
853///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000854bool BugDriver::debugCodeGenerator() {
Dan Gohman70ef4492008-12-08 04:02:47 +0000855 if ((void*)SafeInterpreter == (void*)Interpreter) {
856 std::string Result = executeProgramSafely("bugpoint.safe.out");
Dan Gohmanac95cc72009-07-16 15:30:09 +0000857 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
858 << "the reference diff. This may be due to a\n front-end "
859 << "bug or a bug in the original program, but this can also "
860 << "happen if bugpoint isn't running the program with the "
861 << "right flags or input.\n I left the result of executing "
862 << "the program with the \"safe\" backend in this file for "
863 << "you: '"
864 << Result << "'.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000865 return true;
866 }
867
868 DisambiguateGlobalSymbols(Program);
869
870 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
871
872 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000873 DenseMap<const Value*, Value*> ValueMap;
874 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
875 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000876
877 // Condition the modules
878 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
879
Reid Spencer97182982004-12-15 01:53:08 +0000880 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000881 std::string ErrMsg;
882 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000883 errs() << getToolName() << "Error making unique filename: "
884 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000885 exit(1);
886 }
Reid Spencer97182982004-12-15 01:53:08 +0000887
Chris Lattner74382b72009-08-23 22:45:37 +0000888 if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
889 errs() << "Error writing bitcode to `" << TestModuleBC.str()
890 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000891 exit(1);
892 }
893 delete ToCodeGen;
894
895 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000896 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000897 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000898 errs() << getToolName() << "Error making unique filename: "
899 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000900 exit(1);
901 }
Reid Spencer97182982004-12-15 01:53:08 +0000902
Chris Lattner74382b72009-08-23 22:45:37 +0000903 if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
904 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
905 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000906 exit(1);
907 }
Chris Lattner74382b72009-08-23 22:45:37 +0000908 std::string SharedObject = compileSharedObject(SafeModuleBC.str());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000909 delete ToNotCodeGen;
910
Dan Gohmanac95cc72009-07-16 15:30:09 +0000911 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000912 if (isExecutingJIT()) {
Chris Lattner74382b72009-08-23 22:45:37 +0000913 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000914 } else {
Chris Lattner74382b72009-08-23 22:45:37 +0000915 outs() << " llc -f " << TestModuleBC.str() << " -o " << TestModuleBC.str()
916 << ".s\n";
917 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
918 << ".s -o " << TestModuleBC.str() << ".exe";
Chris Lattner59615f02005-01-15 00:07:19 +0000919#if defined (HAVE_LINK_R)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000920 outs() << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000921#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000922 outs() << "\n";
Chris Lattner74382b72009-08-23 22:45:37 +0000923 outs() << " " << TestModuleBC.str() << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000924 }
925 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000926 outs() << " " << InputArgv[i];
927 outs() << '\n';
928 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattner74382b72009-08-23 22:45:37 +0000929 << SafeModuleBC.str() << " -o temporary.c\n"
Daniel Dunbarca740962009-08-18 03:35:57 +0000930 << " gcc -xc temporary.c -O2 -o " << SharedObject;
931 if (TargetTriple.getArch() == Triple::sparc)
932 outs() << " -G"; // Compile a shared library, `-G' for Sparc
933 else
934 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
935
936 outs() << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000937
938 return false;
939}