blob: 116e3a53715f4fd3a33b003151d2b782d2b1e243 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Chris Lattnera57d86b2004-04-05 22:58:16 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000020#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000021#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000022#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000023#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.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 {
32 extern cl::list<std::string> InputArgv;
33}
34
Chris Lattnerefdc0b52004-03-14 20:50:42 +000035namespace {
Reid Spencerdc31a8a2006-11-11 19:05:02 +000036 static llvm::cl::opt<bool>
37 DisableLoopExtraction("disable-loop-extraction",
38 cl::desc("Don't extract loops when searching for miscompilations"),
39 cl::init(false));
40
Chris Lattnerfa761832004-01-14 03:38:37 +000041 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
42 BugDriver &BD;
43 public:
44 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000045
Chris Lattnerfa761832004-01-14 03:38:37 +000046 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
47 std::vector<const PassInfo*> &Suffix);
48 };
49}
Chris Lattner640f22e2003-04-24 17:02:17 +000050
Misha Brukman8c194ea2004-04-21 18:36:43 +000051/// TestResult - After passes have been split into a test group and a control
52/// group, see if they still break the program.
53///
Chris Lattner640f22e2003-04-24 17:02:17 +000054ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000055ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000056 std::vector<const PassInfo*> &Suffix) {
57 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000058 // with JUST the kept passes, discard the prefix passes.
Chris Lattner06943ad2003-04-25 03:16:05 +000059 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +000060 << "' compile correctly: ";
61
62 std::string BytecodeResult;
Chris Lattner06943ad2003-04-25 03:16:05 +000063 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +000064 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000065 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000066 BD.setPassesToRun(Suffix);
67 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000068 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000069 }
70
71 // Check to see if the finished program matches the reference output...
Misha Brukman50733362003-07-24 18:17:43 +000072 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +000073 std::cout << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000074 if (Suffix.empty()) {
75 std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
76 << "no passes are run, nondeterministic program?\n";
77 exit(1);
78 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000079 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000080 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000081 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000082
83 if (Prefix.empty()) return NoFailure;
84
Chris Lattner06943ad2003-04-25 03:16:05 +000085 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000086 // then separately run the "kept" passes.
Chris Lattner640f22e2003-04-24 17:02:17 +000087 std::cout << "Checking to see if '" << getPassesString(Prefix)
88 << "' compile correctly: ";
89
90 // If it is not broken with the kept passes, it's possible that the prefix
91 // passes must be run before the kept passes to break it. If the program
92 // WORKS after the prefix passes, but then fails if running the prefix AND
93 // kept passes, we can update our bytecode file to include the result of the
94 // prefix passes, then discard the prefix passes.
95 //
96 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +000097 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000098 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000099 BD.setPassesToRun(Prefix);
100 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000101 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000102 }
103
104 // If the prefix maintains the predicate by itself, only keep the prefix!
Misha Brukman50733362003-07-24 18:17:43 +0000105 if (BD.diffProgram(BytecodeResult)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +0000106 std::cout << " nope.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000107 sys::Path(BytecodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000108 return KeepPrefix;
109 }
Misha Brukman123f8fe2004-04-22 20:02:09 +0000110 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000111
112 // Ok, so now we know that the prefix passes work, try running the suffix
113 // passes on the result of the prefix passes.
114 //
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000115 Module *PrefixOutput = ParseInputFile(BytecodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000116 if (PrefixOutput == 0) {
117 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
118 << BytecodeResult << "'!\n";
119 exit(1);
120 }
Reid Spencera229c5c2005-07-08 03:08:58 +0000121 sys::Path(BytecodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000122
123 // Don't check if there are no passes in the suffix.
124 if (Suffix.empty())
125 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000126
Chris Lattner06943ad2003-04-25 03:16:05 +0000127 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000128 << "' passes compile correctly after the '"
129 << getPassesString(Prefix) << "' passes: ";
130
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000131 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Chris Lattner06943ad2003-04-25 03:16:05 +0000132 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman3da94ae2005-04-22 00:00:37 +0000133 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +0000134 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000135 BD.setPassesToRun(Suffix);
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000136 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000137 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000138 }
139
140 // Run the result...
Misha Brukman50733362003-07-24 18:17:43 +0000141 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
Misha Brukman123f8fe2004-04-22 20:02:09 +0000142 std::cout << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000144 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000145 }
146
147 // Otherwise, we must not be running the bad pass anymore.
Misha Brukman123f8fe2004-04-22 20:02:09 +0000148 std::cout << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000149 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000150 return NoFailure;
151}
152
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000153namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000154 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
155 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000156 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000157 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000158 ReduceMiscompilingFunctions(BugDriver &bd,
159 bool (*F)(BugDriver &, Module *, Module *))
160 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000161
Chris Lattnerfa761832004-01-14 03:38:37 +0000162 virtual TestResult doTest(std::vector<Function*> &Prefix,
163 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000164 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000165 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000166 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000167 return KeepPrefix;
168 return NoFailure;
169 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000170
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000171 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000172 };
173}
Chris Lattner640f22e2003-04-24 17:02:17 +0000174
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000175/// TestMergedProgram - Given two modules, link them together and run the
176/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000177/// matches, return false, otherwise return true. If the DeleteInputs argument
178/// is set to true then this function deletes both input modules before it
179/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000180///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000181static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
182 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000183 // Link the two portions of the program back to together.
184 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000185 if (!DeleteInputs) {
186 M1 = CloneModule(M1);
187 M2 = CloneModule(M2);
188 }
Reid Spencere4874022004-12-13 03:01:03 +0000189 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000190 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000191 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000192 exit(1);
193 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000194 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000195
196 Module *OldProgram = BD.swapProgramIn(M1);
197
198 // Execute the program. If it does not match the expected output, we must
199 // return true.
200 bool Broken = BD.diffProgram();
201
202 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000203 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000204 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000205 return Broken;
206}
207
Misha Brukman8c194ea2004-04-21 18:36:43 +0000208/// TestFuncs - split functions in a Module into two groups: those that are
209/// under consideration for miscompilation vs. those that are not, and test
210/// accordingly. Each group of functions becomes a separate Module.
211///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000212bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000213 // Test to see if the function is misoptimized if we ONLY run it on the
214 // functions listed in Funcs.
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000215 std::cout << "Checking to see if the program is misoptimized when "
216 << (Funcs.size()==1 ? "this function is" : "these functions are")
217 << " run through the pass"
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000218 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000219 PrintFunctionList(Funcs);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000220 std::cout << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000221
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000222 // Split the module into the two halves of the program we want.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000223 Module *ToNotOptimize = CloneModule(BD.getProgram());
224 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
Chris Lattner640f22e2003-04-24 17:02:17 +0000225
Chris Lattnerb15825b2004-04-05 21:37:38 +0000226 // Run the predicate, not that the predicate will delete both input modules.
227 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000228}
229
Misha Brukman8c194ea2004-04-21 18:36:43 +0000230/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
231/// modifying predominantly internal symbols rather than external ones.
232///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000233static void DisambiguateGlobalSymbols(Module *M) {
234 // Try not to cause collisions by minimizing chances of renaming an
235 // already-external symbol, so take in external globals and functions as-is.
236 // The code should work correctly without disambiguation (assuming the same
237 // mangler is used by the two code generators), but having symbols with the
238 // same name causes warnings to be emitted by the code generator.
239 Mangler Mang(*M);
Andrew Lenharth0fccc742005-12-06 20:51:30 +0000240 // Agree with the CBE on symbol naming
241 Mang.markCharUnacceptable('.');
Chris Lattnerafd39f02006-09-07 18:21:07 +0000242 Mang.setPreserveAsmNames(true);
Chris Lattner67ef9e42006-05-04 23:35:31 +0000243 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
244 I != E; ++I)
Chris Lattner36ee07f2004-04-11 23:52:35 +0000245 I->setName(Mang.getValueName(I));
246 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
247 I->setName(Mang.getValueName(I));
248}
249
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000250/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
251/// check to see if we can extract the loops in the region without obscuring the
252/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000253///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000254static bool ExtractLoops(BugDriver &BD,
255 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000256 std::vector<Function*> &MiscompiledFunctions) {
257 bool MadeChange = false;
258 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000259 if (BugpointIsInterrupted) return MadeChange;
260
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000261 Module *ToNotOptimize = CloneModule(BD.getProgram());
262 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
263 MiscompiledFunctions);
264 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
265 if (!ToOptimizeLoopExtracted) {
266 // If the loop extractor crashed or if there were no extractible loops,
267 // then this chapter of our odyssey is over with.
268 delete ToNotOptimize;
269 delete ToOptimize;
270 return MadeChange;
271 }
272
273 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000274
275 // Bugpoint is intentionally not very trusting of LLVM transformations. In
276 // particular, we're not going to assume that the loop extractor works, so
277 // we're going to test the newly loop extracted program to make sure nothing
278 // has broken. If something broke, then we'll inform the user and stop
279 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000280 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000281 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000282 BD.switchToInterpreter(AI);
283
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000284 // Merged program doesn't work anymore!
285 std::cerr << " *** ERROR: Loop extraction broke the program. :("
286 << " Please report a bug!\n";
287 std::cerr << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000288
289 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
290 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
291 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
292 ToOptimizeLoopExtracted);
293
294 std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
295 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000296 delete ToNotOptimize;
297 delete ToOptimizeLoopExtracted;
298 return MadeChange;
299 }
Chris Lattner56c41862005-05-08 21:54:56 +0000300 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000301 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000302
Chris Lattnerb15825b2004-04-05 21:37:38 +0000303 std::cout << " Testing after loop extraction:\n";
304 // Clone modules, the tester function will free them.
305 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
306 Module *TNOBackup = CloneModule(ToNotOptimize);
307 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
308 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000309 // If the program is not still broken, then loop extraction did something
310 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000311 delete TOLEBackup;
312 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000313 return MadeChange;
314 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000315 ToOptimizeLoopExtracted = TOLEBackup;
316 ToNotOptimize = TNOBackup;
317
318 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000319
Chris Lattner90c18c52004-11-16 06:31:38 +0000320 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
321 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
322 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000323 if (!I->isExternal())
324 MisCompFunctions.push_back(std::make_pair(I->getName(),
325 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000326
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000327 // Okay, great! Now we know that we extracted a loop and that loop
328 // extraction both didn't break the program, and didn't mask the problem.
329 // Replace the current program with the loop extracted version, and try to
330 // extract another loop.
331 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000332 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000333 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000334 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000335 exit(1);
336 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000337 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000338
339 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000340 // module. Update this list to include all of the functions in the
341 // optimized and loop extracted module.
342 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000343 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
344 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
345 MisCompFunctions[i].second);
346 assert(NewF && "Function not found??");
347 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000348 }
349
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000350 BD.setNewProgram(ToNotOptimize);
351 MadeChange = true;
352 }
353}
354
Chris Lattner5e783ab2004-05-11 21:54:13 +0000355namespace {
356 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
357 BugDriver &BD;
358 bool (*TestFn)(BugDriver &, Module *, Module *);
359 std::vector<Function*> FunctionsBeingTested;
360 public:
361 ReduceMiscompiledBlocks(BugDriver &bd,
362 bool (*F)(BugDriver &, Module *, Module *),
363 const std::vector<Function*> &Fns)
364 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000365
Chris Lattner5e783ab2004-05-11 21:54:13 +0000366 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
367 std::vector<BasicBlock*> &Suffix) {
368 if (!Suffix.empty() && TestFuncs(Suffix))
369 return KeepSuffix;
370 if (TestFuncs(Prefix))
371 return KeepPrefix;
372 return NoFailure;
373 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000374
Chris Lattner5e783ab2004-05-11 21:54:13 +0000375 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
376 };
377}
378
379/// TestFuncs - Extract all blocks for the miscompiled functions except for the
380/// specified blocks. If the problem still exists, return true.
381///
382bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
383 // Test to see if the function is misoptimized if we ONLY run it on the
384 // functions listed in Funcs.
Chris Lattner68bee932004-05-12 16:08:01 +0000385 std::cout << "Checking to see if the program is misoptimized when all ";
386 if (!BBs.empty()) {
387 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
388 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
389 std::cout << BBs[i]->getName() << " ";
390 if (BBs.size() > 10) std::cout << "...";
391 } else {
392 std::cout << "blocks are extracted.";
393 }
Misha Brukmaneed80e22004-07-23 01:30:49 +0000394 std::cout << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000395
396 // Split the module into the two halves of the program we want.
397 Module *ToNotOptimize = CloneModule(BD.getProgram());
398 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
399 FunctionsBeingTested);
400
401 // Try the extraction. If it doesn't work, then the block extractor crashed
402 // or something, in which case bugpoint can't chase down this possibility.
403 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
404 delete ToOptimize;
405 // Run the predicate, not that the predicate will delete both input modules.
406 return TestFn(BD, New, ToNotOptimize);
407 }
408 delete ToOptimize;
409 delete ToNotOptimize;
410 return false;
411}
412
413
414/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
415/// extract as many basic blocks from the region as possible without obscuring
416/// the bug.
417///
418static bool ExtractBlocks(BugDriver &BD,
419 bool (*TestFn)(BugDriver &, Module *, Module *),
420 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000421 if (BugpointIsInterrupted) return false;
422
Chris Lattner5e783ab2004-05-11 21:54:13 +0000423 std::vector<BasicBlock*> Blocks;
424 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
425 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
426 E = MiscompiledFunctions[i]->end(); I != E; ++I)
427 Blocks.push_back(I);
428
429 // Use the list reducer to identify blocks that can be extracted without
430 // obscuring the bug. The Blocks list will end up containing blocks that must
431 // be retained from the original program.
432 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000433
434 // Check to see if all blocks are extractible first.
435 if (ReduceMiscompiledBlocks(BD, TestFn,
436 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
437 Blocks.clear();
438 } else {
439 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
440 if (Blocks.size() == OldSize)
441 return false;
442 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000443
Chris Lattner2290e752004-05-12 02:43:24 +0000444 Module *ProgClone = CloneModule(BD.getProgram());
445 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
446 MiscompiledFunctions);
447 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
448 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000449 // Weird, extraction should have worked.
Chris Lattner2290e752004-05-12 02:43:24 +0000450 std::cerr << "Nondeterministic problem extracting blocks??\n";
451 delete ProgClone;
452 delete ToExtract;
453 return false;
454 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000455
Chris Lattner2290e752004-05-12 02:43:24 +0000456 // Otherwise, block extraction succeeded. Link the two program fragments back
457 // together.
458 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000459
Chris Lattner90c18c52004-11-16 06:31:38 +0000460 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
461 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
462 I != E; ++I)
Chris Lattnerfa1af132004-11-19 07:09:40 +0000463 if (!I->isExternal())
464 MisCompFunctions.push_back(std::make_pair(I->getName(),
465 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000466
Chris Lattner2290e752004-05-12 02:43:24 +0000467 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000468 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Chris Lattner2290e752004-05-12 02:43:24 +0000469 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukmaneed80e22004-07-23 01:30:49 +0000470 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000471 exit(1);
472 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000473 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000474
Chris Lattner2290e752004-05-12 02:43:24 +0000475 // Set the new program and delete the old one.
476 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000477
Chris Lattner2290e752004-05-12 02:43:24 +0000478 // Update the list of miscompiled functions.
479 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000480
Chris Lattner90c18c52004-11-16 06:31:38 +0000481 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
482 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
483 MisCompFunctions[i].second);
484 assert(NewF && "Function not found??");
485 MiscompiledFunctions.push_back(NewF);
486 }
Chris Lattner2290e752004-05-12 02:43:24 +0000487
488 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000489}
490
491
Chris Lattnerb15825b2004-04-05 21:37:38 +0000492/// DebugAMiscompilation - This is a generic driver to narrow down
493/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000494///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000495static std::vector<Function*>
496DebugAMiscompilation(BugDriver &BD,
497 bool (*TestFn)(BugDriver &, Module *, Module *)) {
498 // Okay, now that we have reduced the list of passes which are causing the
499 // failure, see if we can pin down which functions are being
500 // miscompiled... first build a list of all of the non-external functions in
501 // the program.
502 std::vector<Function*> MiscompiledFunctions;
503 Module *Prog = BD.getProgram();
504 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
505 if (!I->isExternal())
506 MiscompiledFunctions.push_back(I);
507
508 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000509 if (!BugpointIsInterrupted)
510 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000511
512 std::cout << "\n*** The following function"
513 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
514 << " being miscompiled: ";
515 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000516 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000517
518 // See if we can rip any loops out of the miscompiled functions and still
519 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000520
521 if (!DisableLoopExtraction)
522 if (!BugpointIsInterrupted &&
523 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000524 // Okay, we extracted some loops and the problem still appears. See if we
525 // can eliminate some of the created functions from being candidates.
526
Chris Lattner36ee07f2004-04-11 23:52:35 +0000527 // Loop extraction can introduce functions with the same name (foo_code).
528 // Make sure to disambiguate the symbols so that when the program is split
529 // apart that we can link it back together again.
530 DisambiguateGlobalSymbols(BD.getProgram());
531
Chris Lattnerb15825b2004-04-05 21:37:38 +0000532 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000533 if (!BugpointIsInterrupted)
534 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000535
Chris Lattnerb15825b2004-04-05 21:37:38 +0000536 std::cout << "\n*** The following function"
537 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
538 << " being miscompiled: ";
539 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000540 std::cout << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000541 }
542
Chris Lattneraed98fa2005-08-02 23:25:56 +0000543 if (!BugpointIsInterrupted &&
544 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000545 // Okay, we extracted some blocks and the problem still appears. See if we
546 // can eliminate some of the created functions from being candidates.
547
548 // Block extraction can introduce functions with the same name (foo_code).
549 // Make sure to disambiguate the symbols so that when the program is split
550 // apart that we can link it back together again.
551 DisambiguateGlobalSymbols(BD.getProgram());
552
553 // Do the reduction...
554 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000555
Chris Lattner5e783ab2004-05-11 21:54:13 +0000556 std::cout << "\n*** The following function"
557 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
558 << " being miscompiled: ";
559 PrintFunctionList(MiscompiledFunctions);
Misha Brukmaneed80e22004-07-23 01:30:49 +0000560 std::cout << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000561 }
562
Chris Lattnerb15825b2004-04-05 21:37:38 +0000563 return MiscompiledFunctions;
564}
565
Chris Lattnera57d86b2004-04-05 22:58:16 +0000566/// TestOptimizer - This is the predicate function used to check to see if the
567/// "Test" portion of the program is misoptimized. If so, return true. In any
568/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000569///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000570static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
571 // Run the optimization passes on ToOptimize, producing a transformed version
572 // of the functions being tested.
573 std::cout << " Optimizing functions being tested: ";
574 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
575 /*AutoDebugCrashes*/true);
576 std::cout << "done.\n";
577 delete Test;
578
579 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000580 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000581 std::cout << (Broken ? " nope.\n" : " yup.\n");
582 return Broken;
583}
584
585
Chris Lattner4a106452002-12-23 23:50:16 +0000586/// debugMiscompilation - This method is used when the passes selected are not
587/// crashing, but the generated output is semantically different from the
588/// input.
589///
590bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000591 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000592 if (!BugpointIsInterrupted)
593 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
594 std::cerr << "*** Optimized program matches reference output! No problem"
595 << " detected...\nbugpoint can't help you with your problem!\n";
596 return false;
597 }
Chris Lattner4a106452002-12-23 23:50:16 +0000598
Chris Lattner640f22e2003-04-24 17:02:17 +0000599 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000600 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
Misha Brukmaneed80e22004-07-23 01:30:49 +0000601 << getPassesString(getPassesToRun()) << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000602 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000603
Chris Lattnerb15825b2004-04-05 21:37:38 +0000604 std::vector<Function*> MiscompiledFunctions =
605 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000606
Chris Lattner640f22e2003-04-24 17:02:17 +0000607 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000608 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000609 Module *ToNotOptimize = CloneModule(getProgram());
610 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
611 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000612
613 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000614 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000615 EmitProgressBytecode("tonotoptimize", true);
616 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000617
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000618 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000619 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000620 EmitProgressBytecode("tooptimize");
621 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000622
Chris Lattner4a106452002-12-23 23:50:16 +0000623 return false;
624}
Brian Gaeked0fde302003-11-11 22:41:34 +0000625
Chris Lattnera57d86b2004-04-05 22:58:16 +0000626/// CleanupAndPrepareModules - Get the specified modules ready for code
627/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000628///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000629static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
630 Module *Safe) {
631 // Clean up the modules, removing extra cruft that we don't need anymore...
632 Test = BD.performFinalCleanups(Test);
633
634 // If we are executing the JIT, we have several nasty issues to take care of.
635 if (!BD.isExecutingJIT()) return;
636
637 // First, if the main function is in the Safe module, we must add a stub to
638 // the Test module to call into it. Thus, we create a new function `main'
639 // which just calls the old one.
640 if (Function *oldMain = Safe->getNamedFunction("main"))
641 if (!oldMain->isExternal()) {
642 // Rename it
643 oldMain->setName("llvm_bugpoint_old_main");
644 // Create a NEW `main' function with same type in the test module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000645 Function *newMain = new Function(oldMain->getFunctionType(),
Chris Lattnera57d86b2004-04-05 22:58:16 +0000646 GlobalValue::ExternalLinkage,
647 "main", Test);
648 // Create an `oldmain' prototype in the test module, which will
649 // corresponds to the real main function in the same module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000650 Function *oldMainProto = new Function(oldMain->getFunctionType(),
Chris Lattnera57d86b2004-04-05 22:58:16 +0000651 GlobalValue::ExternalLinkage,
652 oldMain->getName(), Test);
653 // Set up and remember the argument list for the main function.
654 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000655 for (Function::arg_iterator
656 I = newMain->arg_begin(), E = newMain->arg_end(),
657 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000658 I->setName(OI->getName()); // Copy argument names from oldMain
659 args.push_back(I);
660 }
661
662 // Call the old main function and return its result
663 BasicBlock *BB = new BasicBlock("entry", newMain);
Chris Lattnerfa1af132004-11-19 07:09:40 +0000664 CallInst *call = new CallInst(oldMainProto, args, "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000665
Chris Lattnera57d86b2004-04-05 22:58:16 +0000666 // If the type of old function wasn't void, return value of call
Chris Lattnerfa1af132004-11-19 07:09:40 +0000667 new ReturnInst(call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000668 }
669
670 // The second nasty issue we must deal with in the JIT is that the Safe
671 // module cannot directly reference any functions defined in the test
672 // module. Instead, we use a JIT API call to dynamically resolve the
673 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000674
Chris Lattnera57d86b2004-04-05 22:58:16 +0000675 // Add the resolver to the Safe module.
676 // Prototype: void *getPointerToNamedFunction(const char* Name)
Misha Brukman3da94ae2005-04-22 00:00:37 +0000677 Function *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000678 Safe->getOrInsertFunction("getPointerToNamedFunction",
679 PointerType::get(Type::SByteTy),
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000680 PointerType::get(Type::SByteTy), (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000681
Chris Lattnera57d86b2004-04-05 22:58:16 +0000682 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000683 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000684 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
685 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000686 Function *TestFn = Test->getNamedFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000687
688 // Don't forward functions which are external in the test module too.
689 if (TestFn && !TestFn->isExternal()) {
690 // 1. Add a string constant with its name to the global file
691 Constant *InitArray = ConstantArray::get(F->getName());
692 GlobalVariable *funcName =
693 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000694 GlobalValue::InternalLinkage, InitArray,
Chris Lattnera57d86b2004-04-05 22:58:16 +0000695 F->getName() + "_name", Safe);
696
697 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
698 // sbyte* so it matches the signature of the resolver function.
699
700 // GetElementPtr *funcName, ulong 0, ulong 0
701 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
702 Value *GEP =
Reid Spencer518310c2004-07-18 00:44:37 +0000703 ConstantExpr::getGetElementPtr(funcName, GEPargs);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000704 std::vector<Value*> ResolverArgs;
705 ResolverArgs.push_back(GEP);
706
Misha Brukmande4803d2004-04-19 03:36:47 +0000707 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
708 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000709 if (!F->use_empty()) {
710 // Create a new global to hold the cached function pointer.
711 Constant *NullPtr = ConstantPointerNull::get(F->getType());
712 GlobalVariable *Cache =
713 new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
714 NullPtr,F->getName()+".fpcache", F->getParent());
Jeff Cohen00b168892005-07-27 06:12:32 +0000715
Misha Brukmande4803d2004-04-19 03:36:47 +0000716 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000717 const FunctionType *FuncTy = F->getFunctionType();
Misha Brukmande4803d2004-04-19 03:36:47 +0000718 Function *FuncWrapper = new Function(FuncTy,
719 GlobalValue::InternalLinkage,
Misha Brukmandc7fef82004-04-19 01:12:01 +0000720 F->getName() + "_wrapper",
721 F->getParent());
Chris Lattnera3efca12005-07-12 01:00:32 +0000722 BasicBlock *EntryBB = new BasicBlock("entry", FuncWrapper);
723 BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper);
724 BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000725
Chris Lattnera3efca12005-07-12 01:00:32 +0000726 // Check to see if we already looked up the value.
727 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
728 Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal,
729 NullPtr, "isNull", EntryBB);
730 new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000731
Misha Brukmande4803d2004-04-19 03:36:47 +0000732 // Resolve the call to function F via the JIT API:
733 //
734 // call resolver(GetElementPtr...)
Chris Lattnera3efca12005-07-12 01:00:32 +0000735 CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs,
736 "resolver", LookupBB);
Misha Brukmande4803d2004-04-19 03:36:47 +0000737 // cast the result from the resolver to correctly-typed function
Chris Lattnera3efca12005-07-12 01:00:32 +0000738 CastInst *CastedResolver =
739 new CastInst(Resolver, PointerType::get(F->getFunctionType()),
740 "resolverCast", LookupBB);
741 // Save the value in our cache.
742 new StoreInst(CastedResolver, Cache, LookupBB);
743 new BranchInst(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000744
Chris Lattnera3efca12005-07-12 01:00:32 +0000745 PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB);
746 FuncPtr->addIncoming(CastedResolver, LookupBB);
747 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000748
Chris Lattnera3efca12005-07-12 01:00:32 +0000749 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000750 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000751 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
752 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000753 Args.push_back(i);
754
755 // Pass on the arguments to the real function, return its result
756 if (F->getReturnType() == Type::VoidTy) {
Reid Spencer3ed469c2006-11-02 20:25:50 +0000757 new CallInst(FuncPtr, Args, "", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000758 new ReturnInst(DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000759 } else {
Chris Lattnera3efca12005-07-12 01:00:32 +0000760 CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB);
761 new ReturnInst(Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000762 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000763
Misha Brukmande4803d2004-04-19 03:36:47 +0000764 // Use the wrapper function instead of the old function
765 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000766 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000767 }
768 }
769 }
770
771 if (verifyModule(*Test) || verifyModule(*Safe)) {
772 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
773 abort();
774 }
775}
776
777
778
779/// TestCodeGenerator - This is the predicate function used to check to see if
780/// the "Test" portion of the program is miscompiled by the code generator under
781/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000782///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000783static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
784 CleanupAndPrepareModules(BD, Test, Safe);
785
Reid Spencer97182982004-12-15 01:53:08 +0000786 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000787 std::string ErrMsg;
788 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
789 std::cerr << BD.getToolName() << "Error making unique filename: "
790 << ErrMsg << "\n";
791 exit(1);
792 }
Reid Spencer97182982004-12-15 01:53:08 +0000793 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000794 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
795 exit(1);
796 }
797 delete Test;
798
799 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000800 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000801 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
802 std::cerr << BD.getToolName() << "Error making unique filename: "
803 << ErrMsg << "\n";
804 exit(1);
805 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000806
Reid Spencer97182982004-12-15 01:53:08 +0000807 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000808 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
809 exit(1);
810 }
Reid Spencer97182982004-12-15 01:53:08 +0000811 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000812 delete Safe;
813
814 // Run the code generator on the `Test' code, loading the shared library.
815 // The function returns whether or not the new output differs from reference.
Reid Spencer97182982004-12-15 01:53:08 +0000816 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000817
818 if (Result)
819 std::cerr << ": still failing!\n";
820 else
821 std::cerr << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000822 TestModuleBC.eraseFromDisk();
823 SafeModuleBC.eraseFromDisk();
824 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000825
826 return Result;
827}
828
829
Misha Brukman8c194ea2004-04-21 18:36:43 +0000830/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
831///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000832bool BugDriver::debugCodeGenerator() {
833 if ((void*)cbe == (void*)Interpreter) {
834 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
835 std::cout << "\n*** The C backend cannot match the reference diff, but it "
836 << "is used as the 'known good'\n code generator, so I can't"
837 << " debug it. Perhaps you have a front-end problem?\n As a"
838 << " sanity check, I left the result of executing the program "
839 << "with the C backend\n in this file for you: '"
840 << Result << "'.\n";
841 return true;
842 }
843
844 DisambiguateGlobalSymbols(Program);
845
846 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
847
848 // Split the module into the two halves of the program we want.
849 Module *ToNotCodeGen = CloneModule(getProgram());
850 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
851
852 // Condition the modules
853 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
854
Reid Spencer97182982004-12-15 01:53:08 +0000855 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000856 std::string ErrMsg;
857 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
858 std::cerr << getToolName() << "Error making unique filename: "
859 << ErrMsg << "\n";
860 exit(1);
861 }
Reid Spencer97182982004-12-15 01:53:08 +0000862
863 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000864 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
865 exit(1);
866 }
867 delete ToCodeGen;
868
869 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000870 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000871 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
872 std::cerr << getToolName() << "Error making unique filename: "
873 << ErrMsg << "\n";
874 exit(1);
875 }
Reid Spencer97182982004-12-15 01:53:08 +0000876
877 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000878 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
879 exit(1);
880 }
Reid Spencer97182982004-12-15 01:53:08 +0000881 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000882 delete ToNotCodeGen;
883
884 std::cout << "You can reproduce the problem with the command line: \n";
885 if (isExecutingJIT()) {
886 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
887 } else {
Chris Lattner59615f02005-01-15 00:07:19 +0000888 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000889 std::cout << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattner59615f02005-01-15 00:07:19 +0000890 << ".s -o " << TestModuleBC << ".exe";
891#if defined (HAVE_LINK_R)
Chris Lattner3bd5fac2005-12-14 22:01:07 +0000892 std::cout << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000893#endif
894 std::cout << "\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000895 std::cout << " " << TestModuleBC << ".exe";
896 }
897 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
898 std::cout << " " << InputArgv[i];
Misha Brukmaneed80e22004-07-23 01:30:49 +0000899 std::cout << '\n';
Chris Lattnera57d86b2004-04-05 22:58:16 +0000900 std::cout << "The shared object was created with:\n llc -march=c "
901 << SafeModuleBC << " -o temporary.c\n"
902 << " gcc -xc temporary.c -O2 -o " << SharedObject
903#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
904 << " -G" // Compile a shared library, `-G' for Sparc
905#else
906 << " -shared" // `-shared' for Linux/X86, maybe others
907#endif
908 << " -fno-strict-aliasing\n";
909
910 return false;
911}